Array VS Type[] in Typescript

2020-01-30 08:20发布

As far as I know a property's type can be defined in two ways when it's an Array.

property_name: type

where type can be either

Array<string>, Array<MyType>, etc. (e.g. let prop1: Array<string>)

and

string[], MyType[], etc. (e.g. let prop1: string[])

What is the difference between the two cases? Or am I misunderstanding something (perhaps something about <> used in casting?)

EDIT since the question is marked as duplicate, I am aware there is the other question about any[] but still I had a look at it before posting and to me it was more about the type 'any' than the different [] VS <> I asked

标签: typescript
2条回答
Animai°情兽
2楼-- · 2020-01-30 08:35
foo: Array

means that it's a plain array, with an implicit any type for it's members

foo: string[]

means that it's an array of strings, i.e. TypeScript will go mental if you try pushing anything other than strings into that array.

查看更多
够拽才男人
3楼-- · 2020-01-30 08:45

There isn't any semantic difference

There is no difference at all. Type[] is the shorthand syntax for an array of Type. Array<Type> is the generic syntax. They are completely equivalent.

The handbook provides an example here. It is equivalent to write:

function loggingIdentity<T>(arg: T[]): T[] {
    console.log(arg.length);
    return arg;
}

Or:

function loggingIdentity<T>(arg: Array<T>): Array<T> {
    console.log(arg.length);
    return arg;
}

And here is a quote from some release notes:

Specifically, number[] is a shorthand version of Array<number>, just as Date[] is a shorthand for Array<Date>.

However, there is a case where the shorthand syntax is required

Since TypeScript 3.4, there is a difference for the new readonly type modifier. Indeed:

the readonly type modifier can only be used for syntax on array types and tuple types

let err1: readonly Set<number>; // error!
let err2: readonly Array<boolean>; // error!

let okay: readonly boolean[]; // works fine
查看更多
登录 后发表回答