ruk·si

🏷️ TypeScript
Tuples

Updated at 2024-08-02 06:15
  • Arrays in TypeScript can be of any length and contain any type defined.
  • Tuples are arrays with a fixed number of elements and types.
const nameAge: [string, number] = ["Bob", 42];
let yearAndWarrior: [number, string];
yearAndWarrior = [530, "Tomyris"];
yearAndWarrior = ["530", "Tomyris"]; // error
yearAndWarrior = [530];              // error

You can force an array to const with as const. It also makes the tuple read-only.

const unionArray = [1157, "Tomoe"];             // (string | number)[]
const readonlyTuple = [1157, "Tomoe"] as const; // readonly [1157, "Tomoe"]

Tuples are a great way to return multiple values if you don't want to bother yourself with objects.

function firstCharAndSizeExplicit(input: string): [string, number] {
    return [input[0], input.length];
}
const [first, size] = firstCharAndSizeExplicit("Cathay Williams");

Sources

  • Learning TypeScript by Josh Goldberg