Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - Typescript Array vs 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);

When you call this function with static data, TypeScript uses a typed array (type[]).

mergeArrays([true, false],  [1, 2]);
//          bool[]          number[]

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 = [[], []];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The previous answer to this question has been outdated for a while now.

First of all Array requires a generic parameter:

var arr: Array<any>;

This is equivalent to:

var arr: any[];

Types Array<any> and any[] are identical and both refer to arrays with variable/dynamic size.

Typescript 3.0 introduced Tuples, which are like arrays with fixed/static size, but not really.

Let me explain.

Their syntax looks like this:

var arr: [any];
var arr: [any, any];
var arr: [any, any, any];
var arr: [string, number, string?, MyType];

Typescript will force you to assign an array of that length and with values that have the matching types.
And when you index the array typescript will recognize the type of variable at that index.

It's interesting to note that typescript wont stop you from modifying the size of the Tuple, either by using a function like .push() or by assigning a value to length. So you have to make sure you don't do it by accident.

You can also specify a "rest" type for any extra elements:

var arr: [any, any, ...any[]];
var arr: [string, number, string?, MyType, ...YourType[]];

In which case you can assign more items to the Tuple and the size of the array may change.

Note: You can not assign a normal array to a Tuple.

In case you only specify a rest type, then you get a regular old array.
The following 2 expressions are equivalent:

var arr: [...any[]];
var arr: any[];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...