24.3.2021 |

TypeScript static inheritance Quiz

Following Situation:

abstract class Animal {
  static makeNoise = () => "Wild Animal Noises";

  constructor() {
    console.log(Animal.makeNoise());
  }
}

class Dog extends Animal {
  static makeNoise = () => "Wild Dog Noises";
}

class Cat extends Animal {
  static makeNoise = () => "Wild Cat Noises";
}

new Cat();
new Dog();

What will be logged?

Antwort 2x `Wild Animal Noises`

Okay, now we want the function to log the child classes makeNoise function result, how can we do it?

Antwort
    const child = this.constructor as typeof Animal;

    console.log(child.makeNoise());

We had to use this when working with ngxs, where selectors are static functions. We had an Abstract State that we extended with different child states so there was no way to call the right function without using this method.

Play with the example here: https://codesandbox.io/s/loving-ellis-kivbb?file=/src/index.ts

Zur Übersicht

Mehr vom DevSquad...

Lucas Meurer

Debug NodeJS with Intellij

Kerstin Paduch

Cypress & Network Stubbing