L
L
Leel Usama2022-01-26 21:55:22
JavaScript
Leel Usama, 2022-01-26 21:55:22

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}`;
  }
}


phrase belongs to Animal-derived classes. How to describe it in typescript?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-01-26
@leelusama

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 question

Ask a Question

731 491 924 answers to any question