principletypescriptCritical
Array<Type> VS Type[] in Typescript
Viewed 0 times
arraytypetypescript
Problem
As far as I know a property's type can be defined in two ways when it's an array:
where type can be either
and
What is the difference between the two cases? Or am I misunderstanding something (perhaps something about
property_name: typewhere type can be either
Array
Array
// etc. (e.g. let prop1: Array)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)?Solution
There isn't any semantic difference
There is no difference at all.
The handbook provides an example here. It is equivalent to write:
Or:
And here is a quote from some release notes:
Specifically,
About the
TypeScript 3.4, introduces the
the
The following declaration is equivalent to
There is no difference at all.
Type[] is the shorthand syntax for an array of Type. Array is the generic syntax. They are completely equivalent.The handbook provides an example here. It is equivalent to write:
function loggingIdentity(arg: T[]): T[] {
console.log(arg.length);
return arg;
}Or:
function loggingIdentity(arg: Array): Array {
console.log(arg.length);
return arg;
}And here is a quote from some release notes:
Specifically,
number[] is a shorthand version of Array, just as Date[] is a shorthand for Array.About the
readonly type modifierTypeScript 3.4, introduces the
readonly type modifier. With a precision:the
readonly type modifier can only be used for syntax on array types and tuple typeslet err2: readonly Array; // error!
let okay: readonly boolean[]; // works fineThe following declaration is equivalent to
readonly boolean[]:let okay2: ReadonlyArray;Code Snippets
function loggingIdentity<T>(arg: T[]): T[] {
console.log(arg.length);
return arg;
}function loggingIdentity<T>(arg: Array<T>): Array<T> {
console.log(arg.length);
return arg;
}let err2: readonly Array<boolean>; // error!
let okay: readonly boolean[]; // works finelet okay2: ReadonlyArray<boolean>;Context
Stack Overflow Q#36842158, score: 474
Revisions (0)
No revisions yet.