【问题标题】:Typescript: Why type alias satisfies a constraint but same interface doesn't?打字稿:为什么类型别名满足约束但相同的接口不满足?
【发布时间】:2021-03-16 17:33:20
【问题描述】:

我遇到了这个奇怪的案例。我声明了一个条件类型。对于相同的extends 约束,类型别名满足它,而结构相同的接口则不满足。

我很迷茫,为什么会有不同?检查playground

interface Constraint {
  [key: string]: string | number | boolean
}

type ATypeAlias = {
  str: string
  num: number
  bool: boolean
}

interface SameInterface {
  str: string
  num: number
  bool: boolean
}

type expectToBeTrue = ATypeAlias extends Constraint ? true : false

// Wat???
type butWhyAmIFalse = SameInterface extends Constraint ? true : false

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您遇到了一个已知问题,microsoft/TypeScript#15300implicit index signatures 被推断为类型别名,而不是接口。这是类型别名和接口在类型分析中不同的少数几个地方之一。根据@RyanCavanaugh(Microsoft TypeScript 团队的开发负责人),这是by design:

    只是为了填补人们的空白,这种行为目前是设计使然。因为接口可以通过额外的声明来扩充,但类型别名不能,所以推断类型别名的隐式索引签名比接口的隐式索引签名“更安全”(在那个上面加了重引号)。 但如果看起来有意义的话,我们也会考虑为接口做这件事。 [强调]

    好的,目前是设计使然,但 GitHub 问题的状态(截至 2019 年 4 月 23 日)是“建议”和“讨论中”。因此,如果您希望看到这种变化,您可能需要 go there 并给问题一个 ? 或描述您的用例(如果它特别引人注目)。

    希望有所帮助;祝你好运!

    【讨论】:

    • 感谢您的回复和链接。我不明白为什么它“更安全”:-/
    猜你喜欢
    • 2019-09-12
    • 2019-09-12
    • 1970-01-01
    • 2019-09-19
    • 2021-09-20
    • 2021-01-28
    • 1970-01-01
    • 2022-11-10
    • 2020-10-25
    相关资源
    最近更新 更多