typescript - 接口(interface)不能扩展条件类型中的映射类型

标签 typescript interface conditional-types mapped-types

在调试我的程序时,我注意到以下示例会产生编译错误 ( 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'.

似乎接口(interface)无法扩展 Record<string, unknown>而类型可以。我知道 TypeScript 中的类型和接口(interface)之间存在一些差异,我怀疑映射类型不能在接口(interface)中使用这一事实可能解释了这种行为。我无法完全理解为什么此 map 类型限制会导致 Qux正在never不过,即使是这样。

此外,interface Foobar extends Record<string, unknown> { key: string };是一个有效的接口(interface)定义,这让我对错误更加困惑。

谁能帮我理解这个错误?

最佳答案

那是因为类型别名具有隐式索引签名,但接口(interface)没有。

如果您要将索引签名添加到接口(interface) - Qux 将导致 any:

interface Bar { 
    key: string;
    [p: string]: string;
};

Playground

更多信息 here :

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.

关于typescript - 接口(interface)不能扩展条件类型中的映射类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65559426/

相关文章:

javascript - 刷新后 Angular $超时

class - Kotlin 为枚举类值方法定义接口(interface)

c# - 分配给委托(delegate)的通用方法

typescript - 联合数据类型上的条件数据类型

json - 在 Typescript 中解析 JSON 数组

angular - HTML输入元素 : how to raise angular event handler after the text was changed

Typescript:依赖于同一对象中另一个属性的属性的类型

javascript - 将条件类型映射回联合类型?

angular - 插值数据不起作用

java - 如何将变量类型设置为 "something that implements these two interfaces"?