1 | initial version |
One way to ensure that sub-classes have uniform method parameters in TypeScript is by using an abstract class with an abstract method. Abstract classes cannot be instantiated directly and must be subclassed. The abstract method in the abstract class can define the uniform method parameters that sub-classes must implement. Here's an example:
abstract class Animal {
abstract makeSound(sound: string): void;
}
class Dog extends Animal {
makeSound(sound: string) {
console.log(`Bark: ${sound}`);
}
}
class Cat extends Animal {
makeSound(sound: string) {
console.log(`Meow: ${sound}`);
}
}
const dog = new Dog();
dog.makeSound('woof'); // outputs "Bark: woof"
const cat = new Cat();
cat.makeSound('purr'); // outputs "Meow: purr"
In the above example, the Animal
abstract class defines the makeSound
method with a sound
parameter. Both the Dog
and Cat
classes must implement the makeSound
method with a sound
parameter, ensuring uniformity across sub-classes.