Describe the shape of an object

INPUT · Slides

Fields you can leave out, and fields you never change

01 / 06

Put ? on something that might not be there

Real data has fields that some people have and others do not — a nickname that some have registered and some have not.

For a property like that, put a ? after the name. It means you do not have to write this one.

interface Person {  name: string;  nickname?: string;}const yui: Person = { name: "Yui" };console.log(yui);

Result

{ name: "Yui" }

02 / 06

You cannot use a ? field as it is

Once you write ?, TypeScript starts thinking "there might be nothing in there".

So it stops you using it without checking. That is the "possibly 'undefined'" message. It is showing you a bug that really does happen, ahead of time.

interface Person {  name: string;  nickname?: string;}const yui: Person = { name: "Yui" };console.log(yui.nickname.length);

Result

Type error: 'yui.nickname' is possibly 'undefined'.

03 / 06

Check with !== undefined, then use it

Check whether something is in there with an if, and inside it TypeScript agrees that "here, there is something".

You write if (variable.field !== undefined) {. The type is reminding you of the plainly sensible step of checking before you use it.

interface Person {  name: string;  nickname?: string;}const rin: Person = {  name: "Rin",  nickname: "Rinny",};if (rin.nickname !== undefined) {  console.log(rin.nickname);}

Result

Rinny

04 / 06

Put readonly on something you do not want changed

The other way round, some fields should not change once they are made — a membership number, a student number.

Put readonly in front of the name of a property like that. Anything without it stays changeable as before.

interface Member {  readonly id: number;  name: string;}const m: Member = { id: 7, name: "Yui" };m.name = "Yuiko";console.log(m);

Result

{ id: 7, name: "Yuiko" }

05 / 06

Assign to a readonly field and it stops

Try to assign to a field you marked readonly and you get an error on that line.

A comment saying "please do not touch this directly" sometimes goes unread. Write it in the type and it holds even when nobody reads it.

interface Member {  readonly id: number;  name: string;}const m: Member = { id: 7, name: "Yui" };m.id = 9;

Result

Type error: Cannot assign to 'id' because it is a read-only property.

06 / 06

A few characters, and much less room to break

? and readonly are only a few characters each. With that, you leave the rules of your data — "might not be there", "must not change" — written into the code.

With them written down, the next person to touch it does not need to know the rules. The type will stop them. Let us write some.