为什么泛型的属性约束因接口而不是类型而失败

时间:2019-01-05 19:34:56

标签: typescript

看看这个片段:

type Constrained<T extends { [K in string]: string }> = T;

type A = {
    p: string;
}

interface B {
    p: string;
}

type R1 = Constrained<A>; // Why this is OK...
type R2 = Constrained<B>; // ... and this an Error?

playground

例如,我知道可以用不同的方式表达约束以避免错误,

type Constrained<T extends { [K in keyof T]: string }> = T;

及其类似的解决方案可以在herehere中找到。

我的问题是:为什么interface失败了,而type却没有失败?

我的猜测是因为interface是开放式的(可以扩展/合并)。

0 个答案:

没有答案