TypeScript Arrays

TypeScript tutorial

TypeScript Arrays

In TypeScript arrays are used to store multiple values of the same type.

TypeScript adds type safety to arrays so you can’t accidentally insert the wrong type.

 Declaring Arrays

Method 1: Using type[]

Method 2: Using Array<type>

  • Both are valid (first is more common).

Array with Type Inference

TypeScript automatically infers array types.

Error:

 Mixed Type Arrays (Union Types)

Use union types to allow multiple types.

Array of Objects

 Readonly Arrays

Prevent array modification.

 Not allowed:

Tuple vs Array

Tuple has fixed length & types, array doesn’t.

 Common Array Methods (Type-Safe)


 

TypeScript ensures:

  •  Correct return types
  •  Correct input

Multidimensional Arrays

 Array with any (Avoid)

  •  Avoid unless absolutely needed.

 Arrays Summary

FeatureExample
Number Arraynumber[]
String Arraystring[]
Generic ArrayArray<number>
Mixed Types`(number
Readonlyreadonly string[]
Objects{}[]
2D Arraynumber[][]

Best Practices

  •  Prefer type[] syntax
  •  Avoid any[]
  •  Use union types for mixed arrays
  • Use readonly when modification isn’t needed

You may also like...