Describe the shape of an object

INPUT · Slides

Adding types to objects

01 / 05

An object has a shape too

An object is a container that holds several named values together. It is the { name: "Yui" } you have been writing since the JavaScript course.

In TypeScript you write down which named values go inside as part of the type. You just line up name: type inside {}.

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

Result

{ name: "Yui" }

02 / 05

Separate the properties with ;

When there is more than one, line the name: type pairs up separated by ;.

Squashed onto one line it gets long, so break the lines and stack them to keep it readable. One look at the type tells you the shape of the object.

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

Result

20

03 / 05

A typo stops you on that very line

Here is the biggest reward for writing this type. Mistype name as nam and it is an error right there.

In JavaScript you would get undefined back, it would slip into a sum, turn into NaN, and you would only notice several lines later. TypeScript even tells you the name it thinks you meant.

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

Result

Type error: Property 'nam' does not exist on type '{ name: string; age: number; }'. Did you mean 'name'?

04 / 05

Leave one out and it is an error

Declare that you will have an age and then forget to put one in, and it is an error at the point you make it.

Once you have said "this is an object of that shape", it will not let you build one that is not complete.

const person: {  name: string;  age: number;} = { name: "Yui" };

Result

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

05 / 05

Too many is an error as well

The other way round, adding a property you never declared is also an error.

It may feel strict, but thanks to this you stop having the accident where a value you thought you put somewhere is never used by anything.

Now that the shape is settled, let us write some.

const person: { name: string } = {  name: "Yui",  age: 20,};

Result

Type error: Object literal may only specify known properties, and 'age' does not exist in type '{ name: string; }'.