DEV Community

Rahul Raj
Rahul Raj

Posted on

Array<Type> vs Type[] vs [Type] in TypeScript

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'];
Enter fullscreen mode Exit fullscreen mode
  • Type[] : It is a simple array of a single type. Ex
const secondArray:string[] = ['alpha','beta','gama'];
Enter fullscreen mode Exit fullscreen mode
  • [Type] : It is a way of defining a tuple, a fixed size array. Ex
const thirdArray:[string, number] = ['alpha', 21];
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
shahrozahmd profile image
Shahroz Ahmed

a quick and helpful guide for me, thanks