Codectionary / Developer documentation / TypeScript

Typing Destructured Parameters

An object parameter can group related options and give callers descriptive field names.

What it is and why to use it

An object parameter can group related options and give callers descriptive field names. Destructuring creates local variables from those fields. The type annotation goes after the complete destructuring pattern, because a colon inside the pattern renames a binding instead.

Common mistakes and limitations

Writing { name: string } in the parameter pattern renames name to a local variable called string; it is not a string type annotation. Destructuring also does not validate a runtime object received from an untrusted source.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

function greet({ name }: { name: string }): string;

Examples

Typing Destructured Parameters

Standalone TypeScript 5.8+ example; expected output is explained below.

type GreetingOptions = { name: string; punctuation?: string };
function greet({ name, punctuation = "!" }: GreetingOptions): string {
  return "Hello, " + name + punctuation;
}
console.log(greet({ name: "John" }));
console.log(greet({ name: "James", punctuation: "." }));
  1. GreetingOptions names the required name and optional punctuation fields.
  2. The parameter destructures both fields; the default applies when punctuation is undefined.
  3. Callers can read the option names directly at the call site. This is useful when a function would otherwise have several easily confused positional arguments.
  4. Expected output: Hello, John! Hello, James.

Best practices

  • Writing { name: string } in the parameter pattern renames name to a local variable called string; it is not a string type annotation. Destructuring also does not validate a runtime object received from an untrusted source.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading