Skip to main content

TypeScript Arrays

TypeScript has a special syntax for typing arrays: write the element type followed by [].

If arrays are new to you, read about JavaScript arrays first.

Example

names is a string[], so it accepts strings but pushing a number would be an error.

Prompt
Show the syntax for typing an array of strings. Declare an empty constant names typed as string[], push "Dylan" (no error), and keep a commented-out names.push(3) with a comment explaining it would fail because a number is not assignable to string. Nothing is printed.
Output: TypeScript file and captured output

Readonly

The readonly keyword stops an array from being changed after it is created.

Example

Because names is readonly string[], methods that change it such as push do not exist on it — calling one is a compile error.

Prompt
Show that the readonly modifier stops an array from being changed. Declare names as readonly string[] holding ["Dylan"], then call names.push("Jack") — the compiler must report "Property 'push' does not exist on type 'readonly string[]'". Add a comment inviting the reader to remove readonly and try again.
Output: TypeScript file and captured output

Type Inference

If an array has values when you create it, TypeScript can infer (work out) its type from them.

Example

numbers is inferred as number[]. Pushing another number is fine, but pushing a string is an error, and reading numbers[0] gives a number.

Prompt
Show TypeScript inferring number[] for an array literal and enforcing it. Declare numbers = [1, 2, 3] with no annotation, push 4 (no error), then push the string "2" — that line must fail with "Argument of type 'string' is not assignable to parameter of type 'number'". Finally assign numbers[0] to a number variable head (no error).
Output: TypeScript file and captured output