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

Lucas

Softwareentwickler

Zur Übersicht

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund