Employee extends Person in TypeScript
10 An employee that extends a person
easyWrite a person class with a name and an age. Then write an employee class extending it, whose constructor also takes an employee id.
Stuck? Three hints, smallest first
- 1. The child constructor takes all three values and passes two of them to
super(). - 2. Declare the extra field as a parameter property to keep it short.
- 3. Override
describe()and callsuper.describe()so the parent’s part is not rewritten.
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)}`)
);
}
class Person {
constructor(
public name: string,
public age: number,
) {}
describe(): string {
return `${this.name}, ${this.age}`;
}
}
class Employee extends Person {
constructor(name: string, age: number, public employeeId: string) {
super(name, age);
}
override describe(): string {
return `${super.describe()}, staff id ${this.employeeId}`;
}
}
const p = new Person('Amaka Obi', 31);
const e = new Employee('Chidi Eze', 28, 'EMP-0042');
console.log(p.describe());
console.log(e.describe());
test('the parent alone', p.describe(), 'Amaka Obi, 31');
test('the child adds to it', e.describe(), 'Chidi Eze, 28, staff id EMP-0042');
test('inherited fields are there', e.age, 28);
test('and the new one', e.employeeId, 'EMP-0042');
test('an Employee is a Person', e instanceof Person, true);
Output
The override keyword on describe is not decoration. With noImplicitOverride switched on, a method that replaces a parent method must say so, which means renaming the parent’s method turns every stale child into a compile error instead of a silent behaviour change.