TypeScript satisfies

Feb-21, 2025 · 1min

使一个表达式符合某个类型,而不改变表达式的类型。

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>'.
// 这里会报错,因为 bleu 不是 Colors 类型 } // 这里会报错,因为 palette.green 可能是 string 类型,也可能是 RGB 类型,而 string 类型没有 toUpperCase 方法 const = ..toUpperCase()
Property 'toUpperCase' does not exist on type 'string | RGB'. Property 'toUpperCase' does not exist on type 'RGB'.

使用 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>'.
// 这里会报错,因为 bleu 不是 Colors 类型 } satisfies <, string | > // 这里不会报错,因为 palette.green 是 string 类型,有 toUpperCase 方法 const = ..()

这里使用 satisfies 后,palette 符合 Record<Colors, string | RGB> 类型,并且保留了其原有的类型,所以这个推断 palette.green 是 string 类型

其他使用场景

确保对象的 keys 符合某个类型

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

// 确保对象的 keys 符合 Colors 类型
const  = {
  : 'yes',
  : false,
  : 'kinda',
  platypus: false,
Object literal may only specify known properties, and 'platypus' does not exist in type 'Record<Colors, unknown>'.
// 错误:platypus 没有在 Colors 类型中列出 } satisfies <, unknown> // 所有关于 'red', 'green', 和 'blue' 属性的信息都被保留了,不是 unknown 类型 const : boolean = .

确保对象的属性值符合某个类型

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

// 确保对象的属性值符合 string 和 RGB 类型
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.
// 错误:blue 的类型既不是 string 类型,也不是 RGB 类型 } satisfies <string, string | > // 每个属性的信息仍然被保留。 const = ..(0) // red 是 RGB 类型 const = ..() // green 是 string 类型