TypeScript satisfies

Feb-21, 2025 ยท 1min

change language

Deeply understand the usage of the TypeScript satisfies operator, ensuring type safety while maintaining type inference, improving code quality and development experience

Make an expression conform to a type, without changing the type of the expression.

type  = 'red' | 'green' | 'blue'
type  = [: number, : number, : number]

const : <, string | > = {
  : [255, 0, 0],
  : '#00ff00',
  bleu: [0, 0, 255],
Object literal may only specify known properties, and 'bleu' does not exist in type 'Record<Colors, string | RGB>'.
// It will report an error because bleu is not a Colors type } // It will report an error because palette.green may be a string type, or an RGB type, and the string type does not have a toUpperCase method const = ..toUpperCase()
Property 'toUpperCase' does not exist on type 'string | RGB'. Property 'toUpperCase' does not exist on type 'RGB'.

Using satisfies

type  = 'red' | 'green' | 'blue'
type  = [: number, : number, : number]

const  = {
  : [255, 0, 0],
  : '#00ff00',
  bleu: [0, 0, 255],
Object literal may only specify known properties, and 'bleu' does not exist in type 'Record<Colors, string | RGB>'.
// It will report an error because bleu is not a Colors type } satisfies <, string | > // It will not report an error because palette.green is a string type, and has a toUpperCase method const = ..()

After using satisfies, palette conforms to the Record<Colors, string | RGB> type, and retains its original type, so this inference palette.green is a string type

Other usage scenarios

Ensure that the keys of the object conform to a certain type

type  = 'red' | 'green' | 'blue'

// Ensure that the keys of the object conform to the Colors type
const  = {
  : 'yes',
  : false,
  : 'kinda',
  platypus: false,
Object literal may only specify known properties, and 'platypus' does not exist in type 'Record<Colors, unknown>'.
// It will report an error because platypus is not a Colors type } satisfies <, unknown> // All information about the 'red', 'green', and 'blue' properties is retained, not unknown type const : boolean = .

Ensure that the property values of the object conform to a certain type

type  = [: number, : number, : number]

// Ensure that the property values of the object conform to the string and RGB type
const  = {
  : [255, 0, 0],
  : '#00ff00',
  blue: [0, 0],
Type '[number, number]' is not assignable to type 'string | RGB'. Type '[number, number]' is not assignable to type 'RGB'. Source has 2 element(s) but target requires 3.
// It will report an error because the type of blue is neither a string type nor an RGB type } satisfies <string, string | > // The information about each property is still retained. const = ..(0) // red is an RGB type const = ..() // green is a string type