📱 Erkannter Endgerättyp 🔇 Sound ist aus. ⛱️ Tag und Nacht. Verbraucht keinen oder einen 🍪.
guest
Login 🗃️ Speicher- und Dateiverwaltung 🍪 0 Anzahl Ihrer gespeicherten Kekse, führt zur Keksdose

Inheritance in JS

Small detail i sometimes trip.

When you have 2 classes, one extends from another you can redefine a method in the Sub to take no arguments even though the Base defines them

class Base {
    public method(entries: number[]): void {
        console.log(entries);
    }
}

class Sub extends Base {
    // Sub doesn't care about 'entries'
    public method(): void {
        console.log("no parameters needed!");
    }
    super([123]) ← this would however need them
}

Reverse is not true and will complain

class Base {
    public method(): void {
        console.log("huhu");
    }
}

// will error
class Sub extends Base {
    public method(entries: number[]): void {  ← property in ... is not assignable to ... etc
        console.log(entries);
    }
}

Why

When you call method with an argument and use the Sub which does not expect them thats fine because these are never used.

  • Both methods can run when an argument is sent so in both cases success possible

But it would error if you call Base or Sub without arguments because in one case they are expected and used.

Example from simple baked in functions

// The official signature of Array.prototype.forEach is:
// (value: T, index: number, array: T[]) => void

[1, 2, 3].forEach((val) => {
    console.log(val);
});

because you only use val argument in your function definition but still all 3 are sent this would error if we forced to use all 3.

Types in Functions

Method bivariance

You cannot disable this with compiler flags.

TS allows types to mismatch

class Animal { name = "animal"; }
class Dog extends Animal { bark() {} }

class Parent {
    makeSound(animal: Animal) {}
}

class Child extends Parent {
    // TS allows this with method syntax, even though it's technically unsafe!
    makeSound(dog: Dog) {
        dog.bark();
    }
}

so DOM event hierarchies (like Event vs MouseEvent) work smoothly without fighting the type checker.

Property syntax

watch out and not do this for lots of instances in an engine! You can however do

class Parent {
    makeSound: (animal: Animal) => void = (animal) => {
        console.log("generic noise");
    };
}

this needs you to define a function body though which would then run on any instance creation even if never used.

So in engine usage do an interface and implement it

interface ParentContract {
    makeSound: (animal: Animal) => void;
}

... then implement from this

class Child implements ParentContract {
    makeSound(animal) ← will be enfoced to use type Animal not Dog
}

Current PTF

Hintergrund ändern. Verbraucht keinen oder einen 🍪.

Verknüpften Viewport öffnen

🎮 Steuerung
Dokumentation 🕹️
Sie sind leider kein Entwickler :(

Content Nodes Amount

Diligence / PTF Amount

FPS

Vertex-Count