Answer the question
In order to leave comments, you need to log in
How to type a javascript class on typescript?
interface IAnimal {
name: string;
say: () => string;
}
class Animal implements IAnimal {
name: string;
constructor(name: string) {
this.name = name;
}
say() {
return `${this.name} says ${this.phrase}`;
}
}
Answer the question
In order to leave comments, you need to log in
make phrase an abstract field/property and override it in descendants. The child itself can choose whether to make a field or a property.
interface IAnimal {
name: string;
say: () => string;
}
abstract class Animal implements IAnimal {
name: string;
constructor(name: string) {
this.name = name;
}
say() {
return `${this.name} says ${this.phrase}`;
}
protected abstract phrase: string;
}
class Cat extends Animal {
protected get phrase() { return 'm'; }
}
const c = new Cat('q');
console.log(c.say());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question