Generics TS:为什么不能将无效类型分配给泛型类型变量?
不确定如何计算该问题,但实际情况如下:Generics TS:为什么不能将无效类型分配给泛型类型变量?,generics,typescript,Generics,Typescript,不确定如何计算该问题,但实际情况如下: interface X { some: number } let arr1: Array<X> = Array.from([{ some: 1, another: 2 }]) // no error let arr2: Array<X> = Array.from<X>([{ some: 1, another: 2 }]) // will error 接口X{ 一些:数字 } 让arr1:Array=Array.f
interface X {
some: number
}
let arr1: Array<X> = Array.from([{ some: 1, another: 2 }]) // no error
let arr2: Array<X> = Array.from<X>([{ some: 1, another: 2 }]) // will error
接口X{
一些:数字
}
让arr1:Array=Array.from([{some:1,other:2}])//无错误
让arr2:Array=Array.from([{some:1,other:2}])//将出错
()
错误:
Argument of type '{ some: number; another: number; }[]' is not assignable to parameter of type 'ArrayLike<X>'.
Index signatures are incompatible.
Type '{ some: number; another: number; }' is not assignable to type 'X'.
Object literal may only specify known properties, and 'another' does not exist in type 'X'.
“{some:number;other:number;}[]”类型的参数不可分配给“ArrayLike”类型的参数。
索引签名不兼容。
类型“{some:number;other:number;}”不可分配给类型“X”。
对象文字只能指定已知属性,并且类型“X”中不存在“另一个”。
为什么在第一种情况下没有错误(没有类型可比性检查),这是设计造成的还是存在问题?让我们看看两个数组实例的类型。
如果去掉类型定义:
// type of arr1 is { some: number; another: number; }[]
let arr1 = Array.from([{ some: 1, another: 2 }]);
// type of arr2 is X[]
let arr2 = Array.from<X>([{ some: 1, another: 2 }]);
您将获得:
Argument of type '{ some: number; }' is not assignable to parameter of type '{ some: number; another: number; }'.
Property 'another' is missing in type '{ some: number; }'.
很有趣,我不知道 看起来任何强类型数组文本只能包含已知的元素。
从错误消息来看,这似乎是设计造成的,而不是错误。此限制不限于阵列,在中有详细说明
arr1.push({ some: 3 });
Argument of type '{ some: number; }' is not assignable to parameter of type '{ some: number; another: number; }'.
Property 'another' is missing in type '{ some: number; }'.