Declare a function with a Tuple return type in TypeScript

avatar

Borislav Hadzhiev

Thu Feb 24 20222 min read

banner

Photo by Brooke Cagle

Declare a function with a Tuple return type in TypeScript #

To declare a function with a tuple return type, set the return type of the function to a tuple right after the function's parameter list, e.g. function getTuple(): [number, number] {}. If the return type of the function is not set, TypeScript will infer it as type[].

index.ts
// ✅ Named function returning tuple function getTuple(): [number, number] { return [5, 10]; } // ✅ Arrow function returning tuple const getTuple2 = (): [string, string] => { return ['hello', 'world']; }; // ✅ Using a type type Numbers = [number, number]; function getTuple4(): Numbers { return [10, 10]; }

You can set the return type of a function right after its parameter list.

To set the return type of a function to a tuple, pass the types of the tuple between square brackets as if passing elements to an array.

index.ts
function getTuple(a: number, b: number): [number, number] { return [a, b]; }

The examples above show how to set the return type of a function to a tuple containing different values.

The advantage of setting the return type of the function explicitly is that the type checker would throw an error if you try to return a tuple of a different type.

index.ts
function getTuple(): [number, number] { // ⛔️ Error: Type '[number, number, number]' // is not assignable to type '[number, number]' return [10, 100, 1000]; }

If you don't explicitly set the return type of the function, TypeScript will infer it to be number[] instead of [number, number].

index.ts
// 👇️ function getTuple(): number[] function getTuple() { return [10, 100]; }

You might also see a const assertion being used in a similar way to how we typed the return value of the function.

index.ts
// 👇️ function getTuple3(): readonly [10, 10] function getTuple3() { return [10, 10] as const; }

The function in the example returns a readonly array containing 2 numbers with value of 10.

There are a couple of differences between the two approaches. Note that if you don't explicitly set the type as readonly or use a const assertion, it can still be mutated.

index.ts
function getTuple(): [number, number] { return [10, 100]; } const t = getTuple(); t.push(1000); console.log(t); // 👉️ [10, 100, 1000]

If you want to use this approach but want the tuple to be readonly, pass the return type of the function to the Readonly utility type.

index.ts
function getTuple(): Readonly<[number, number]> { return [10, 100]; } const t = getTuple(); // ⛔️ Error: Property 'push' does not // exist on type 'readonly [number, number]'.ts(2339) t.push(1000);

The Readonly utility type constructs a type with all properties set to readonly.

Use the search field on my Home Page to filter through my more than 1,000 articles.