Add types to your classes

INPUT · Slides

Type the fields of a class

01 / 05

Write it as you did in JavaScript and you get told off

Bring a class from the JavaScript course straight over into TypeScript and it goes red. All it does inside the constructor is put a value into this.name.

What you get is "Property 'name' does not exist on type 'Person'". To TypeScript a class is also a blueprint for what data it holds, so it will not let something you never declared spring up out of nowhere.

class Person {  constructor(name: string) {    this.name = name;  }}

Result

Type error: Property 'name' does not exist on type 'Person'.

02 / 05

Write down what it holds, first

The fix is easy. Right under the { of the class, write the name and type of each thing it holds, one per line. Each of these is called a field.

Once declared, this.name belongs to this class. After that you assign to it as you did in JavaScript, and read it from outside.

class Person {  name: string;  constructor(name: string) {    this.name = name;  }}const p = new Person("Yui");console.log(p.name);

Result

Yui

03 / 05

Declare it and you must fill it

Declare it but never assign in the constructor and you get a different error: "Property 'name' has no initializer and is not definitely assigned in the constructor."

It is a mouthful, but what it says is "you said you would hold this, and you have not put anything in it". Remember that declaring and assigning come as a pair.

class Person {  name: string;  constructor() {  }}

Result

Type error: Property 'name' has no initializer and is not definitely assigned in the constructor.

04 / 05

Type the methods too

The types of a method's parameters and return are written exactly as on an ordinary function. Parameter types inside the brackets, the return type after them.

The fields you read through this. are typed as well, so mixing up text and numbers turns up here too.

class Person {  name: string;  constructor(name: string) {    this.name = name;  }  call(title: string): string {    return this.name + title;  }}const p = new Person("Yui");console.log(p.call(" san"));

Result

Yui san

05 / 05

Show one and you see only the fields

Hand an instance straight to console.log and out come the fields it holds, in the shape of an object. Methods do not appear.

Handy when you want to check the contents all at once. If you only want one, name the property, as in p.name. Right, have a go.

class Person {  name: string;  age: number;  constructor(name: string, age: number) {    this.name = name;    this.age = age;  }}const p = new Person("Yui", 20);console.log(p);

Result

{ name: "Yui", age: 20 }