Arrays, tuples, and enums¶
This lesson covers ordered collections, fixed-length tuples, and the two kinds of enums available in TypeScript.
Arrays¶
An array type is written with T[] or Array<T>.
TypeScript infers array types from the literals.
For arrays that should not change, add readonly.
Array methods¶
Common methods keep their types.
const numbers = [1, 2, 3, 4]
const doubled = numbers.map((n) => n * 2) // number[]
const evens = numbers.filter((n) => n % 2 === 0) // number[]
const first = numbers.find((n) => n > 2) // number | undefined
const sum = numbers.reduce((acc, n) => acc + n, 0) // number
Tuples¶
A tuple has a fixed length and a type for each position.
Named tuples can improve readability.
Readonly arrays and tuples¶
Prevent mutation with readonly.
Enums¶
String and numeric enums¶
Numeric enums default to 0, 1, 2. String enums require explicit values.
Const enums¶
const enum values are inlined at compile time and leave no runtime object.
Warning
Non-const enum creates a real JavaScript object. Many teams prefer string literal unions over enum to avoid the runtime object.
Prefer literal unions¶
For closed sets of strings, a union is usually simpler.
This produces no runtime code and works well with narrowing and autocompletion.
Hands-on: schedule tracker¶
- Create
src/schedule.ts. - Define a
type Day = 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri'. - Define
interface Taskwithtitle,durationMinutes, andday: Day. - Create an array
tasks: Task[]with at least three tasks. - Use
filterto find all tasks for'Mon'. - Use
mapto produce an array of strings in the form'Title - X minutes'. - Use
reduceto total the duration of all tasks. - Create a
readonly [string, number]tuple nameddailyLimitand try to reassign one of its elements.