【发布时间】:2021-04-10 01:18:00
【问题描述】:
在调试我的程序时,我注意到以下示例产生了编译错误 (playground)。
type Foo = {key: string};
interface Bar {key: string};
type Baz = Foo extends Record<string, unknown>? any: never;
type Qux = Bar extends Record<string, unknown>? any: never;
const baz: Baz = 0;
const qux: Qux = 0; // Type 'number' is not assignable to type 'never'.
似乎接口不能扩展 Record<string, unknown> 而类型可以。我知道 TypeScript 中的类型和接口之间存在一些差异,我怀疑映射类型不能在接口中使用这一事实可能会解释这种行为。我无法完全理解为什么这种地图类型限制会导致 Qux 成为 never,即使是这样。
此外,interface Foobar extends Record<string, unknown> { key: string }; 是一个有效的接口定义,这让我更加困惑。
谁能帮我理解这个错误?
【问题讨论】:
标签: typescript interface conditional-types mapped-types