Hone

Lessons · TypeScript · typed fields and parameter properties

Fields are declared with their types

In TypeScript a class declares each field and its type before the constructor assigns it. A parameter property, constructor(public name: string), declares and assigns in one line.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The compiler checks every this.something against the declared shape, so a typo in a field name is caught where it is written, and every caller knows exactly what an object carries.

How to think about it

List what every object of this kind holds, with a type each. Write the field lines, or move them into the constructor as parameter properties when each is set straight from an argument.

Worked example

class Dog {
  name: string;
Declare the field and its type.
  constructor(name: string) { this.name = name; }
Then assign it.
}
class Cat {
  constructor(public name: string) {}
A parameter property: declared and assigned in one go.
}
console.log(new Dog('Rex').name, new Cat('Tom').name);
Rex Tom

Your turn

Declare the field the constructor assigns.

class Account {
  : number;
  constructor(balance: number) { this.balance = balance; }
}

The trap

Assigning this.age in the constructor without declaring age. JavaScript allows it; TypeScript says property 'age' does not exist on type 'Dog'.

Practise typed fields and parameter properties on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.