Junior — Middle
How does TypeScript support the concept of polymorphism in types and classes?
sobes.tech AI
Answer from AI
TypeScript supports polymorphism through class inheritance and interfaces, as well as through generic types (generics). Classes can inherit from each other, override methods and properties, which allows using subclass objects where superclass objects are expected (subtyping).
Example with classes:
class Animal {
speak() {
console.log('Animal makes a sound');
}
}
class Dog extends Animal {
speak() {
console.log('Woof');
}
}
function makeSpeak(animal: Animal) {
animal.speak();
}
const dog = new Dog();
makeSpeak(dog); // Outputs: Woof
Generic types allow creating functions and classes that work with different types while maintaining type safety:
type Wrapper<T> = {
value: T;
};
function wrap<T>(x: T): Wrapper<T> {
return { value: x };
}
const wrappedNumber = wrap(42); // Wrapper<number>
const wrappedString = wrap('hello'); // Wrapper<string>
Thus, TypeScript implements polymorphism through inheritance, interfaces, and generics, enabling the writing of flexible and type-safe code.