输入'{a:number; }”不可分配给类型“ T1”

时间:2019-07-01 06:35:08

标签: typescript typescript-typings

为什么对象{ a: number; }无法分配给类型'T1'?

以下代码:

type T = { a: number };

class A<T1 extends T> {
    constructor(public x: T1 = { a: 1 }){}
};
Type '{ a: number; }' is not assignable to type 'T1'.
  '{ a: number; }' is assignable to the constraint of type 'T1', 
  but 'T1' could be instantiated with a different subtype of constraint 'T'.

1 个答案:

答案 0 :(得分:2)

原因很简单。这里的T1T的扩展,因此任何T1也是T,但反之则不然。取决于T1是什么,{a:1}可能无法分配给T1。考虑以下示例:

type TT = T & {b:string};
new A<TT>();

那么在构造函数中会发生什么?由于您没有传递参数x,因此它将为{a:1}使用默认值x,但是显然{a:1}不是TT

相关问题