TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by '[]' to denote an array of that element type:
var list:number[] = [1, 2, 3];
The second way uses a generic array type, Array:
var list:Array<number> = [1, 2, 3];
Are there any difference between these two syntax? Is there a good reason for 2 ways to write these? (I know generics are a thing in other languages but I've never used generics in any past lang).
They are equivalent. The number[]
form is shorthand for the Array<number>
generic.
The "array type literal" from section 3.7.4 of the spec is defined as:
An array type literal references an array type (section 3.3.2) with the given element type.
The "array type" from section 3.3.2 are described as:
Array types are named type references created from the generic interface type 'Array' in the global module with the array element type as a type argument.
This notes that arrays are defined as a generic type with an argument. The generic is the definitive version, but that description is followed immediately by:
Array type literals (section 3.7.4) provide a shorthand notation for creating such references.
There is no difference, the type[]
form exists as a shorthand using pre-existing JS patterns.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments