typescript :为什么类型别名满足约束但相同的接口(interface)不满足?

标签 typescript

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

我很迷茫,为什么不一样?检查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

最佳答案

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

Just to fill people in, this behavior is currently by design. Because interfaces can be augmented by additional declarations but type aliases can't, it's "safer" (heavy quotes on that one) to infer an implicit index signature for type aliases than for interfaces. But we'll consider doing it for interfaces as well if that seems to make sense. [emphasis added]

好的,它是当前设计的,但 GitHub 问题的状态(截至 2019 年 4 月 23 日)是“建议”和“讨论中”。所以如果你想看到这个改变,你可能想要 go there并给问题一个 👍 或描述您的用例(如果它特别引人注目)。

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

关于 typescript :为什么类型别名满足约束但相同的接口(interface)不满足?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814516/

相关文章:

javascript - 带有 dotenv 和 TypeScript 的环境变量

typescript - vue类组件继承,方法来自基类 "is not a function"

macos - 从 shell 命令运行 typescript 编译器 - 权限被拒绝

Javascript 位掩码

javascript - 用Typescript发布NPM软件包的正确方法

typescript Jest 全局变量示例

reactjs - typescript react : Conditionally optional props based on the type of another prop

javascript - typescript - 使用日期时无法更新对象数组

javascript - typescript 路径映射未在 Node 应用程序中翻译

javascript - Typescript 返回值或柯里化(Currying)函数