Describe the shape of an object

INPUT · Slides

Giving a type a name

01 / 05

Writing the same shape over and over is a chore

You will have felt it in the last lesson. An object type has to be written out in full for every variable and every function parameter.

And changing it is worse. Want to add one property, and you have to find every place you wrote it and fix them all. Miss one and you get an error.

So instead, give the shape a name.

02 / 05

Name it with type

Write type Name = shape; and the shape has a name. By custom the name starts with a capital letter, which makes it easy to tell from a variable.

Once it has a name, all you write where the type goes is that one word.

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

Result

{ name: "Yui", age: 20 }

03 / 05

Make it once, use it as often as you like

However many objects of that shape you make, all you write is the one word Person.

Want to add a property? Fix the type declaration in that one place. If anything is then missing where you used it, TypeScript will tell you about every one.

type Person = {  name: string;  age: number;};const a: Person = { name: "Yui", age: 20 };const b: Person = { name: "Rin", age: 21 };console.log(a.age + b.age);

Result

41

04 / 05

It works for parameters and return types too

A named type can go anywhere a type can go — a function parameter, a return type, a variable.

Your function headings fit on one line again, and what goes in and what comes out is clear at a glance.

type Person = {  name: string;  age: number;};function callBy(p: Person): string {  return p.name + "!";}console.log(callBy({ name: "Minato", age: 22 }));

Result

Minato!

05 / 05

The errors use the name as well

The error for a missing property mentions the name you gave. Told "required in type Person", you know at once which declaration to go and look at.

Naming a shape is also an explanation for whoever reads it — yourself in three days included. Let us write some.

type Person = {  name: string;  age: number;};const p: Person = { name: "Yui" };

Result

Type error: Property 'age' is missing in type '{ name: string; }' but required in type 'Person'.