TS Arrays
A typed array is just an array whose elements all share a type. Two equivalent syntaxes — pick one and stick to it.
The two notations
TS
const nums: number[] = [1, 2, 3]; const names: Array<string> = ['Ada', 'Linus'];
Most codebases use T[] for short types and Array<T> for complex ones (e.g. Array<{ id: number; name: string }>).
Mixed-type arrays
TS
const mixed: (string | number)[] = ['Ada', 36];
mixed.forEach(item => {
if (typeof item === 'string') {
console.log(item.toUpperCase());
} else {
console.log(item.toFixed(2));
}
});
Readonly arrays
TS
const days: readonly string[] = ['Mon', 'Tue', 'Wed'];
// days.push('Sun'); // ✗ error — Property 'push' does not exist
// days[0] = 'Hi'; // ✗ error
const days2: ReadonlyArray<string> = ['Mon', 'Tue']; // equivalent
Array methods preserve types
TS
const nums = [1, 2, 3, 4]; const doubled = nums.map(n => n * 2); // number[] const evens = nums.filter(n => n % 2 === 0); // number[] const total = nums.reduce((c, n) => c + n, 0); // number const found = nums.find(n => n > 2); // number | undefined
Common pitfall — array index access
By default, arr[i] claims the type is T, even though it could be undefined at runtime:
TS
const xs = [1, 2, 3]; const x = xs[99]; // typed as number — but actually undefined
Turn on noUncheckedIndexedAccess in tsconfig and the type becomes number | undefined — much safer.
Tip: For tuples (fixed length, mixed types) use
[string, number] instead of an array. TS treats them differently.Example
Example
const nums: number[] = [1, 2, 3, 4];
const tags: Array<string> = ['admin', 'dev'];
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);
const total = nums.reduce((c, n) => c + n, 0);
console.log({ doubled, evens, total });
Try it Yourself »
Exercise
Readonly array type using the modifier.
const days:
string[] = ['Mon'];
Eight letters.
Discussion
Loading…