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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-08-16 11:00:00 +0000
Seen: 15 times
Last updated: Sep 11 '22
How can the calculation of matrix determinant be performed using CUDA?
How can code repetition be prevented when using (box)plot functions?
What steps can I take to prevent my webpage from slowing down when all parts of a div are displayed?
How can circles be detected in openCV?
What is the method to determine the most precise categorization of data using Self Organizing Map?
What causes certain images included in an email to fail to load on iPhone/iPad/iOS?