Home > Software engineering >  In typescript, how can I extend a class from it's instance?
In typescript, how can I extend a class from it's instance?

Time:11-09

Hello I am trying to basically inherit the Vehicle class within the Car class without using extends. I am wanting to do this because I am making a browser extension and I do not have access to the class, but I do have access to the instance. This works as expected, but typescript is throwing an error on the Car class line

Class 'Car' incorrectly implements interface 'ICar'.
  Type 'Car' is missing the following properties from type 'ICar': steer, accelerate, brake

If the code works as I expect it does, it should log out "Steering" and "Honking"

https://www.typescriptlang.org/playground/CarExample

interface IVehicle {
    steer(): void;
    accelerate(): void;
    brake(): void;
}

interface ICar extends IVehicle {
    honk(): void;
}

class Vehicle implements IVehicle {
    constructor(){
        console.log("Vehicle created");
    }
    steer(): void {
        console.log("Steering");
    }
    accelerate(): void {
        console.log("Accelerating");
    }
    brake(): void {
        console.log("Braking");
    }
}

class Car implements ICar {
    constructor(veh: IVehicle){
        Object.setPrototypeOf(this, Object.getPrototypeOf(veh));
        Object.assign(this, veh);
        // Even with the two lines above, it is saying that the object is missing the methods, "steer", "accelerate", and "brake"
    }
    honk(): void {
        console.log("Honking");
    }
}

const veh = new Vehicle();
const car = new Car(veh);

console.log(car.steer());
console.log(car.honk());

CodePudding user response:

You need to create a Car interface which extends IVehicle

interface IVehicle {
    steer(): void;
    accelerate(): void;
    brake(): void;
}

interface ICar extends IVehicle {
    honk(): void;
}

class Vehicle implements IVehicle {
    constructor() {
        console.log("Vehicle created");
    }
    steer(): void {
        console.log("Steering");
    }
    accelerate(): void {
        console.log("Accelerating");
    }
    brake(): void {
        console.log("Braking");
    }
}

interface Car extends ICar { } // <----------- SEE THIS CHANGE

class Car {
    constructor(public veh: IVehicle) {
        Object.setPrototypeOf(this, Object.getPrototypeOf(veh));
        Object.assign(this, veh);
        // Even with the two lines above, it is saying that the object is missing the methods, "steer", "accelerate", and "brake"
    }
    honk(): void {
        console.log("Honking");
    }
}

const veh = new Vehicle();
const car = new Car(veh);

console.log(car.steer()); // ok
console.log(car.honk()); // ok

Playground

It is called declaration merging

  • Related