Ask Your Question
0

How can one ensure that sub-classes have uniform method parameters in TypeScript?

asked 2022-08-16 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-09-11 04:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-08-16 11:00:00 +0000

Seen: 9 times

Last updated: Sep 11 '22