TypeScriptBasic types
Arrays: number[] and Array<T>
Array types, where every element has the same type.
Example
#TypeScript
const scores: number[] = [72, 95, 88]
const names: Array<string> = ['Emma', 'Jack']
scores.push(64)
const best = Math.max(...scores)
console.log(best, names.length)Result
95 2
Definition and usage
#You describe an array by adding square brackets to the element type: number[] is an array of numbers, string[] an array of strings. An equivalent notation is the generic type Array<number>.
That way the compiler knows the type of every element and suggests the right methods. After names.map(...), it knows the callback receives a string, and trying to add a number to an array of strings fails.
You write a read-only array as readonly string[] or ReadonlyArray<string>. The compiler then blocks methods that mutate the array, like push().
Syntax
#Syntax
let numbers: number[] = [1, 2, 3]
let strings: Array<string> = ["a", "b"]More examples
#TypeScript
const levels: readonly string[] = ['easy', 'medium', 'hard']
levels.push('expert')
// Error: Property 'push' does not exist on type 'readonly string[]'.TypeScript
const lessons: { title: string; minutes: number }[] = [
{ title: 'Tags', minutes: 12 },
{ title: 'Attributes', minutes: 9 }
]
const total = lessons.reduce((sum, lesson) => sum + lesson.minutes, 0)
console.log(total)Result
21
Good practices
#- Pick one notation (
T[]orArray<T>) and stick with it across the project. You’ll seeT[]more often. - For a fixed-length array with a different type at each position, use a tuple.
Related entries
#- TuplesFixed-length arrays where each position has its own type.
- Object typesA description of an object’s shape: what fields it has and of what type.
- Generics <T>Types and functions with a type parameter that work for many types without losing precision.
- readonlyA modifier that blocks changing a field after the object is created.
- ReadonlyArray<Type>A read-only array: no push, sort, or assignment by index.
Spotted a mistake or missing an example? Write to us.