How do I declare a read-only array tuple in TypeScript?

Solution for TypeScript 3.4+: Const Assertion

With const assertions, the compiler can be told to treat an array or an object as immutable, meaning that their properties are read-only. This also allows the creation of literal tuple types with narrower type inference (i.e. your ["a", "b"] can be of type ["a", "b"], rather than string[] without specifiying the whole thing as a contextual type)

The syntax:

const foo = ["text", 1] as const // or
const foo = <const> ["text", 1]
// typeof foo:
readonly ["text", 1]

It can also be used for object literals:

const myObj = {
  foo: 1,
  bar: ["a", "b"],
  baz: true,
} as const
// typeof myObj:
{ readonly foo: 1, readonly bar: readonly ["a", "b"], readonly baz: true }

Here is the extended information of the corresponding PR.


From Typescript version 3.4 you can just prefix tuple type with readonly keyword (source).

TypeScript 3.4 also introduces new support for readonly tuples. We can prefix any tuple type with the readonly keyword to make it a readonly tuple, much like we now can with array shorthand syntax. As you might expect, unlike ordinary tuples whose slots could be written to, readonly tuples only permit reading from those positions.

function foo(pair: readonly [string, string]) {
    console.log(pair[0]);   // okay
    pair[1] = "hello!";     // error
}

The accepted answer leaves array mutation methods unaffected, which can cause unsoundness in the following way:

const tuple: Readonly<[number, string]> = [0, ''];
tuple.shift();
let a = tuple[0]; // a: number, but at runtime it will be a string

The code below fixes this issue, and includes Sergey Shandar's destructuring fix. You'll need to use --noImplicitAny for it to work properly.

type ArrayItems<T extends ReadonlyArray<any>> = T extends ReadonlyArray<infer TItems> ? TItems : never;

type ExcludeProperties<TObj, TKeys extends string | number | Symbol> = Pick<TObj, Exclude<keyof TObj, TKeys>>;

type ArrayMutationKeys = Exclude<keyof any[], keyof ReadonlyArray<any>> | number;

type ReadonlyTuple<T extends any[]> = Readonly<ExcludeProperties<T, ArrayMutationKeys>> & {
    readonly [Symbol.iterator]: () => IterableIterator<ArrayItems<T>>;
};

const tuple: ReadonlyTuple<[number, string]> = [0, ''];
let a = tuple[0]; // a: number
let b = tuple[1]; // b: string
let c = tuple[2]; // Error when using --noImplicitAny
tuple[0] = 1; // Error
let [d, e] = tuple; // d: number, e: string
let [f, g, h] = tuple; // Error

Since the type [string, number] already is an Array, you can simply use:

Readonly<[string, number]>

Example:

let tuple: Readonly<[string, number]> = ['text', 3, 4, 'another text'];

tuple[0] = 'new text'; //Error (Readonly)

let string1: string = tuple[0]; //OK!
let string2: string = tuple[1]; //Error (Type number)
let number1: number = tuple[0]; //Error (Type string)
let number2: number = tuple[1]; //OK!
let number3: number = tuple[2]; //Error (Type any)

Tags:

Typescript