There are a lot of ways to define array in TypeScript. But when we can use it 🤔? There is no specific rules to use but we can see the differences.
- Array<Type> : It is same as Type[] but is preferred when using different types in the array. Ex
const firstArray:Array<string|number> = [1,2,'alpha'];
- Type[] : It is a simple array of a single type. Ex
const secondArray:string[] = ['alpha','beta','gama'];
- [Type] : It is a way of defining a tuple, a fixed size array. Ex
const thirdArray:[string, number] = ['alpha', 21];
Where we should use the different array formats.
Well it is quite simple to follow.
- When you are having a single datatype and length is unknown then
type[]
can be used. - When the datatype and length both are unknown
Array<type | type>
can be used. - When there is very small size array with specific datatype in each position then Tuple can be used
[string, number]
.
If you like the post follow me for more
Top comments (1)
a quick and helpful guide for me, thanks