打字稿数组与任何[] [英] Typescript Array vs any[]
问题描述
在TypeScript中,数组
和任何[]
之间有什么区别? Array是否引用动态大小的数组(当然是在编译时)和 any []
是指作为参数传递的静态大小的数组并由编译器输入类型?因为目前我有以下函数:
In TypeScript, what is the difference between Array
and any[]
? Does Array refer to dynamically sized arrays (during compile-time, of course) and any[]
refer to statically sized arrays passed as arguments and type-inferred by the compiler? Because currently when I have functions such as:
mergeArrays(arr1 : Array, arr2 : Array);
当您使用静态数据调用此函数时,TypeScript使用类型化数组(键入[]
)。
When you call this function with static data, TypeScript uses a typed array (type[]
).
mergeArrays([true, false], [1, 2]);
// bool[] number[]
那么编译时是否有任何差异? 2?我何时使用任何[]
,何时使用数组
?有时使用 Array定义变量
..
So are there any compile-time differences between the 2? When do I use any[]
and when do I use Array
? Sometimes defining vars with Array
..
var info:Array;
..在设置如下时显示无法将任何[] []转换为数组的错误:
..show errors like "Cannot convert any[][] to Array" when setting as follows:
info = [[], []];
推荐答案
规范第3.5.4节规定了他们的关系:
Spec section 3.5.4 specifies their relationship:
格式的数组类型ElementType []
相当于一个对象类型索引签名[index:number]:ElementType
加上一组等同于全局接口类型Array
的成员,其中所有出现魔法_element
类型替换为ElementType
。
An array type of the form
ElementType[]
is equivalent to an object type with the index signature[index: number]: ElementType
plus a set of members equivalent to the global interface typeArray
where all occurrences of the magic_element
type are replaced withElementType
.
无法分配 [[],[]]
或 []
到数组
是一个错误。
Not being able to assign [[], []]
or []
to Array
is a bug.
TypeScript中没有静态大小数组的概念。他们都在谈论相同的底层JavaScript数组(动态大小):
There is no notion of a "statically-sized" array in TypeScript. They're all talking about the same underlying JavaScript array (which is dynamically sized):
var x = [1, 2];
x.push(3);
x[13] = 5;
这篇关于打字稿数组与任何[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!