rela589n
rela589n

Reputation: 1086

Uncaught TypeError: Super expression must either be null or a function when create child class in parent

There are 2 classes (abstract and concrete). Abstract one creates concrete (i know it is not the best idea, but just for example). In other languages it works just perfectly, but not in javascript. Am I doing anything wrong?

import {Archer} from "@/Entities/Army/Individual/Archer";

export abstract class Unit {
    public abstract bombardStrength(): number;

    public abstract defensiveStrength(): number;

    public getComposite(): void {
        console.log(new Archer());
    }
}

import {Unit} from "@/Entities/Army/Unit";

export class Archer extends Unit {
    bombardStrength(): number {
        return 40;
    }

    defensiveStrength(): number {
        return 35;
    }
}

Why js crashes with this error?

Upvotes: 1

Views: 1723

Answers (2)

zsxeee
zsxeee

Reputation: 66

You cannot import child class in parent class file, because import will lead class declaring, but both have not declared yet.

You need to take getComposite out from Unit to a separate file.

Upvotes: 4

anand shukla
anand shukla

Reputation: 706

The class which implements an abstract class must call super() in the constructor. This is how abstract class works in typescript.

import {Unit} from "@/Entities/Army/Unit";

export class Archer extends Unit {
 constructor(){
 super();    
}
bombardStrength(): number {
    return 40;
}

defensiveStrength(): number {
    return 35;
}
}

This should work just fine.

Upvotes: 0

Related Questions