【问题标题】:interface object couldn't extends Record<string, unknown>接口对象不能扩展 Record<string, unknown>
【发布时间】:2020-11-01 07:39:24
【问题描述】:

为什么接口不能扩展Record

interface Data {
  a: string
}

Data extends Record<string, unknown> ? 'yes' : 'no' // 'no'

但是,如果我将数据更改为类型,它可以正常工作

type Data {
  a: string
}
 
Data extends Record<string, unknown> ? 'yes' : 'no' // 'yes'

【问题讨论】:

  • :) 奇怪的行为。即使您将有条件的Data 接口替换为DataAsType,这将是:type DataGeneric&lt;T&gt; = T; type DataAsType = DataGeneric&lt;Data&gt;; 结果将是相同的。但是如果你用这个{[key in keyof Data]: Data[key]} 替换Data,它会得到yes

标签: typescript


【解决方案1】:

type T = Record&lt;string, unknown&gt; 计算结果为 { [x: string]: unknown; }

对象类型有 implicit index signature,但接口没有 (for safety reasons),因此它们不扩展索引类型。

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 2021-04-24
    • 2022-06-11
    • 2020-12-16
    • 2019-12-04
    • 2021-10-13
    • 2013-09-20
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多