TypeScript 满足运算符和类型断言有什么区别?

问题描述 投票:0回答:1

我最近在 TypeScript 中遇到了

satisfies
运算符,我试图了解它与常规
type assertions
有何不同。两者似乎都提供了一种处理类型的方法,但我不清楚何时使用其中一种。

  • 与类型断言相比,满足运算符如何增强类型安全性?
  • 使用 satisfies 可以捕获哪些类型断言可能会错过的错误?
  • 我什么时候应该更喜欢使用满足而不是类型断言,反之亦然?
// 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;
typescript type-safety type-assertion
1个回答
0
投票

类型断言是一种禁用打字稿的方法。

as Person
告诉打字稿“相信我,我比你知道的更多,它是一个人”。 Typescript 在很大程度上会信任你,所以如果你犯了错误,它不会指出它(它会指出非常严重的错误,然后需要你做
as unknown as Person
来确认你确定) .

satisfies Person
进行了完全类型检查,它告诉打字稿“根据您看到的代码推断类型,但如果结果类型与 Person 不兼容,则给我一个错误”。

© www.soinside.com 2019 - 2024. All rights reserved.