TypeScript 4.9:满足运算符
TypeScript 团队在其 v4.9 版本中发布了一个新的运算符:(satisfies参见博客文章https://devblogs.microsoft.com/typescript/announcing-typescript-4-9-beta/#the-satisfies-operator)。
目的
其目的satisfies是在不改变变量类型的情况下,对变量施加约束。
例如,你想表达一个颜色“要么是字符串,要么是 RGB 元组”,那么结果会是这样的:
type RGB = readonly [red: number, green: number, blue: number];
type Color = { value: RGB | string };
const myColor: Color = { value 'red' };
但是现在,我们不知道它myColor.value是一个字符串还是一个元组。所以我们不能做类似这样的事情myColor.value.toUpperCase()(即使它实际上是一个字符串)。
在 TS 4.9 中,可以这样做(TypeScript Playground):
type RGB = readonly [red: number, green: number, blue: number];
type Color = { value: RGB | string };
const myColor = { value: 'red' } satisfies Color; // works
const myIncorrectColor = { value: 100 } satisfies Color; // throws error
myColor.value.toUpperCase(); // valid operation as myColor is a string
结合as const并满足
正如预期的那样,您可以结合使用as const(satisfiesTypeScript Playground)。
type RGB = readonly [red: number, green: number, blue: number];
type Color = RGB | string;
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [1,2,3],
} satisfies Record<string, Color>;
console.log(palette.green);
// ^? green is string
const constantPalette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [1,2,3],
} as const satisfies Record<string, Color>;
console.log(constantPalette.green);
// ^? green is "#00ff00"
注意:顺序很重要。虽然这样as const satisfies <type>可以运行,但反过来却不行:satisfies <type> as const会抛出一个 TS 错误(TypeScript Playground):
type RGB = readonly [red: number, green: number, blue: number];
type Color = RGB | string;
const invalidPalette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [1,2,3],
} satisfies Record<string, string | RGB> as const; // throws an error