Type modern syntax

INPUT · Slides

Type destructured parameters

01 / 05

Destructuring, with types

Remember pulling names out of an object? const { name, age } = person; from the JavaScript course.

In TypeScript, the variables you pull out get types. The syntax is a little unusual — you write the type after the whole pattern, not after each name.

const person = { name: "Yui", age: 20 };const { name, age }: { name: string; age: number } = person;console.log(name, age);

Result

Yui 20

02 / 05

Best used in function parameters

Destructuring shines brightest in function parameters. Take an object and use its parts straight away.

The type goes as { ... }: { ... } — names on the left, types on the right.

function greet({ name, age }: { name: string; age: number }): string {  return `${name} (${age})`;}console.log(greet({ name: "Kei", age: 25 }));

Result

Kei (25)

03 / 05

A type alias makes it short

Writing the full type every time is long. Give it a name with type and the parameter becomes (p: Person) or ({ name, age }: Person).

Destructuring and type aliases are used together all the time.

type Person = { name: string; age: number };function greet({ name, age }: Person): string {  return `${name} (${age})`;}console.log(greet({ name: "Yui", age: 20 }));

Result

Yui (20)

04 / 05

Pull out only what you need

Even if an object has five properties, destructuring only needs to name the ones you actually use. The type, on the other hand, has to describe every property, including the ones you did not pull out.

Remember the split in roles: the type describes the whole shape of the data, while destructuring picks just what it needs.

type Person = { name: string; age: number; city: string };function onlyName({ name }: Person): string {  return name;}console.log(onlyName({ name: "Rin", age: 30, city: "Kyoto" }));

Result

Rin

05 / 05

A default value for when it is missing

When a property is optional (?), destructuring can give it a default value. Write = defaultValue right after the variable name.

If the value is missing the default is used; if it is present, that value wins.

type Person = { name: string; age?: number };function greet({ name, age = 0 }: Person): string {  return `${name} (${age})`;}console.log(greet({ name: "Yui" }));

Result

Yui (0)