class Animal { speak(): string { return "Generic sound"; } } class Dog extends Animal { speak(): string { return "Woof!"; } } const pet: Animal = new Dog(); console.log(pet.speak());
The variable pet is typed as Animal, but it holds an instance of Dog. When calling pet.speak(), the Dog version of speak runs, returning "Woof!".
TypeScript uses types in inheritance to check that subclasses correctly implement or override properties and methods. This helps catch errors early and ensures safer code.
class Vehicle { speed: number; constructor(speed: number) { this.speed = speed; } } class Car extends Vehicle { speed: string; constructor(speed: string) { super(0); this.speed = speed; } } const myCar = new Car("fast");
The Car class declares speed as a string, but Vehicle declares it as a number. This type conflict causes a TypeScript error.
class Person { name: string; constructor(name: string) { this.name = name; } } class Employee extends Person { employeeId: number; // constructor here }
Option B correctly calls super(name) before assigning this.employeeId and uses the correct type number for employeeId.
Option B uses this before super(), which is invalid.
Option B assigns a string to employeeId which is declared as number.
Option B does not accept employeeId as a parameter.
class Base { baseProp = 1; } class Derived extends Base { derivedProp = 2; } const obj = new Derived();
The instance obj has two own properties: baseProp and derivedProp. Both are assigned directly in the constructors (or property initializers), so obj owns both.