TypeScript Arrays

TypeScript Arrays
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
| Feature | Example |
|---|---|
| Number Array | number[] |
| String Array | string[] |
| Generic Array | Array<number> |
| Mixed Types | `(number |
| Readonly | readonly string[] |
| Objects | {}[] |
| 2D Array | number[][] |
Best Practices
- Prefer
type[]syntax - Avoid
any[] Use union types for mixed arrays- Use
readonlywhen modification isn’t needed
