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

Wir freuen uns Sie kennen zu lernen

Hat Sie unser Angebot überzeugt? Dann freuen wir uns, Sie kennen zu lernen. Kontaktieren Sie uns gerne für ein unverbindliches Erstgespräch.

newcubator GmbH
Freie-Vogel-Straße 369
44269 Dortmund
dortmund@newcubator.com
+49 231/586 873 80
newcubator GmbH
Bödekerstraße 22
30161 Hannover
hannover@newcubator.com
+49 511/957 313 00