2016-10-24 68 views
1

不知道如何如何fomulate的问题,但这样的话:TS:为什么可以将无效类型分配给泛型类型变量?

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 

code in playground

错误:

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'. 

为什么在第一种情况下没有任何错误(没有类型的可比性检查),是由设计还是有这个问题?

回答

1

让我们来看看两个数组实例的类型。
如果我们带走的类型定义:

// 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 }]); 

code in playground:悬停数组变量看类型)

这是因为Array.from的签名是:

from<T>(arrayLike: ArrayLike<T>): Array<T>; 

的编译器不会抱怨arr1,因为它会根据传递给该函数的值推断通用约束。
但是在arr2的情况下,通用约束设置为X,并且类型{ some: number; another: number; }与它不匹配。

如果你尝试添加Xarr1

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; }'. 
1

非常非常有趣,我不知道。

它看起来像任何强类型的数组文字只能包含已知的元素。 从错误消息看,它看起来像是通过设计而不是错误。

+0

此限制不限于数组,并在[本答案](http://stackoverflow.com/a/31816062/43848)中有详细解释, – artem

相关问题