Skip to content
tsCheatSheet
GitHub

Arrays

TypeScript syntax for typing arrays.

const employees: string[] = [];

employees.push('Matt'); // no error because employees is a
// string array.

employees.push(3); // Error: Argument of type 'number'
// is not assignable to parameter of type 'string'.

Readonly

Prevents arrays from being modified.

const employees: readonly string[] = ['Matt'];

employees.push('Michael'); // Error: Property 'push' does
// not exist on type 'readonly string[]'.

Type Inference

Type can be inferred from the array’s initial value.

const employeeIds = [1, 2, 3]; // inferred type = number[].

employeeIds.push(4); // no error, pushing a number.

employeeIds.push('4'); // Error: Argument of type 'string' is
// not assignable to parameter of type 'number'.