Reputation: 15568
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)?
Upvotes: 419
Views: 192057
Reputation: 5294
There is a difference when you are defining fixed length arrays. You can't define a fixed length array with Array<>
, you have to use the shorthand syntax:
const myFunc1 = (arg: [string, number, boolean]) => {
console.log(arg);
};
myFunc1(["hello world", 123, true]);
// error: TS2314: Generic type 'Array ' requires 1 type argument(s).
const myFunc2 = (arg: Array<string, number, boolean>) => {
console.log(arg);
};
myFunc2(["hello world", 123, true])
Upvotes: 7
Reputation: 23772
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 ofArray<number>
, just asDate[]
is a shorthand forArray<Date>
.
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 types
let err2: readonly Array<boolean>; // error!
let okay: readonly boolean[]; // works fine
The following declaration is equivalent to readonly boolean[]
:
let okay2: ReadonlyArray<boolean>;
Upvotes: 468