Syncing account progress…

Back

Advanced · 18 min

Overloads and correlated tuples

Describe related inputs without losing their return or payload types.

Expose precise call signatures

Overloads describe supported calls and their result types. The implementation handles every signature, but its wider signature is not an extra public overload. Prefer a union parameter when callers do not need distinct return types.

function label(value: string): string;
function label(value: number): number;
function label(value: string | number): string | number {
  return typeof value === "string" ? value.trim() : value * 2;
}
console.log(label(" Hi "));
console.log(label(3));

Output

Hi
6

Keep related arguments together

A union of tuples preserves the relationship between a command name and its payload. Narrowing the first tuple entry also narrows the second. Separate unions for the two arguments would permit invalid combinations.

type Command = [kind: "rename", name: string] | [kind: "score", points: number];
function describe(...command: Command): string {
  if (command[0] === "rename") return command[1].toUpperCase();
  return String(command[1] * 2);
}
console.log(describe("score", 4));

Output

8

Put it into practice

  1. Predict the output and explain which relationships the types enforce.
  2. Fix the task while preserving its type contract, then check both practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Repair a correlated command

Pass the number 4 to the score command, keeping the tuple union.

Show solution
type Command = [kind: "rename", name: string] | [kind: "score", points: number];
function describe(...command: Command): string {
  if (command[0] === "rename") return command[1].toUpperCase();
  return String(command[1] * 2);
}
console.log(describe("score", 4));

The tuple union allows only complete valid pairs. The corrected call selects the numeric branch and displays eight.

Practice