TypeScript · 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
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.
Read the function parameter order before changing the tuple.
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.
Put it into practice
- Predict the output and explain which relationships the types enforce.
- Fix the task while preserving its type contract, then check both practice questions.