Class types and inheritance were added to TypeScript to support object-oriented patterns familiar from other languages (Java, C#). TypeScript allows the creation of classes with explicitly defined types for properties and methods, as well as implementing inheritance with type safety.
Without explicit typing in JavaScript, errors associated with incorrect use of properties are not detected at compile time. Problems arise when overriding methods/properties in descendants, violating the base class contract, and improper handling of protected/private members.
TypeScript allows the use of keywords public, private, protected, explicitly specifying types for properties and methods, inheriting classes using extends, and implementing interfaces.
Code example:
class Animal { public name: string; protected age: number; private secret: string = "hidden"; constructor(name: string, age: number) { this.name = name; this.age = age; } speak(): void { console.log(`${this.name} makes a sound.`); } } class Dog extends Animal { constructor(name: string, age: number) { super(name, age); } speak(): void { console.log(`${this.name} barks.`); } } const dog = new Dog("Rex", 4); dog.speak(); // Rex barks.
Key features:
What happens if you don't specify the type of a class field?
TypeScript will attempt to infer the type from the assigned value if available. If not, the type will be any, which decreases code safety.
class Test { value; constructor(v: number) { this.value = v; } }
value will be of type any if no default value is specified — a potential breach of type safety.
Can you change the access modifier of an inherited method?
Yes, but only by strengthening it (for example, from public to protected or private — it is not allowed), whereas from private to public is not possible, since the private member is not inherited. This will result in a compilation error.
Can you inherit from multiple classes in TypeScript?
No, multiple class inheritance is not allowed. You can implement multiple interfaces, but can only extend one class.
In the project, all classes were declared without access modifiers and explicit types, to speed up development.
Pros:
Cons:
All class members are carefully typed, using private/protected/public, strict typing of properties and methods.
Pros:
Cons: