Create a class with a constructor in TypeScript
1 A class with three properties and a constructor
easyWrite a class for a bus with a make, a model and a year. Give it a constructor that fills all three in when the object is created.
Stuck? Three hints, smallest first
- 1. Declare the fields with their types at the top of the class, then assign them in the constructor.
- 2. TypeScript has a shortcut: put
publicin front of each constructor parameter and it declares and assigns the field for you. - 3. Under
strict, a declared field that the constructor never assigns is an error (TS2564).
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
// The long form: declare, then assign.
class Bus {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
}
// The short form. Parameter properties declare and assign in one go.
class BusShort {
constructor(
public make: string,
public model: string,
public year: number,
) {}
}
const a = new Bus('Toyota', 'Coaster', 2019);
const b = new BusShort('Toyota', 'Coaster', 2019);
console.log(a.make, a.model, a.year);
console.log(b.make, b.model, b.year);
test('long form make', a.make, 'Toyota');
test('long form year', a.year, 2019);
test('short form is identical', b.model, 'Coaster');
test('both produce the same data', JSON.stringify(a), JSON.stringify(b));
Output
The two classes produce identical objects. Parameter properties save six lines and are the normal choice for a plain data class. Worth knowing that they are a TypeScript feature, not JavaScript: they compile down to the assignments in the first version.