我最近在 TypeScript 中遇到了
satisfies
运算符,我试图了解它与常规 type assertions
有何不同。两者似乎都提供了一种处理类型的方法,但我不清楚何时使用其中一种。
// Satisfies
interface User1 {
username: string;
passcode: number;
}
const user1 = {
username: "joe",
passcode: 2076,
email: "[email protected]"
} satisfies User1;
// Type Assertion
interface User2 {
username: string;
passcode: number;
}
const user2 = {
username: "doe",
passcode: 3000,
email: "[email protected]"
} as Person;
类型断言是一种禁用打字稿的方法。
as Person
告诉打字稿“相信我,我比你知道的更多,它是一个人”。 Typescript 在很大程度上会信任你,所以如果你犯了错误,它不会指出它(它会指出非常严重的错误,然后需要你做 as unknown as Person
来确认你确定) .
satisfies Person
进行了完全类型检查,它告诉打字稿“根据您看到的代码推断类型,但如果结果类型与 Person 不兼容,则给我一个错误”。