Syncing account progress…

Back

Advanced · 18 min

Inferring function contracts

Derive argument tuples and result types from an existing function.

Keep result shapes in sync

"ReturnType" derives a function result type, avoiding a second manually maintained object shape. For overloaded functions it uses the last signature. These helpers reflect declarations; they do not inspect or call a function at runtime.

function summary(name: string, count: number) { return { label: name, count }; }
type Summary = ReturnType<typeof summary>;
const item: Summary = { label: "Travel", count: 3 };
console.log(item.label + ": " + item.count);

Output

Travel: 3

Reuse the argument tuple

"Parameters" derives a tuple whose order, optional positions, and types match the function. Spreading this tuple supplies correctly ordered arguments. Avoid a broad array when position determines the required type.

function format(name: string, count: number): string { return name + ": " + count; }
type FormatArgs = Parameters<typeof format>;
const args: FormatArgs = ["Music", 2];
console.log(format(...args));

Output

Music: 2

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 function argument tuple

Put "Music" first and 2 second in "args". Keep its derived type and the spread call.

Show solution
function format(name: string, count: number): string { return name + ": " + count; }
type FormatArgs = Parameters<typeof format>;
const args: FormatArgs = ["Music", 2];
console.log(format(...args));

The derived tuple preserves each parameter position. Correcting the values fixes the call without asserting or weakening the tuple type.

Practice