Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot return new derived object from interface function

Tags:

npm

typescript

Typescript code does not compile.

Compiler output: error TS2416: Property 'deepcopy' in type 'Vector2' is not assignable to the same property in base type 'Vector'.

I just started using typescript yesterday and this seems like a trivial issue but cannot seem to find a proper solution to the problem.

interface Vector {
    deepcopy() : this;
}

export class Vector2 implements Vector {
    constructor() {
    }

    deepcopy() {
        return new Vector2();
    }
}

Any suggestions or clues?

like image 364
Sayantan Datta Avatar asked May 04 '26 12:05

Sayantan Datta


1 Answers

interface Vector {
    deepcopy() : Vector;
}

export class Vector2 implements Vector {
    constructor() {
    }

    deepcopy() {
        return new Vector2();
    }
}

The problem with your code is that this is not a type. As a consequence Vector2 does not match it. By changing it to Vector you can return your instance implementing the Vector interface as you want.

like image 153
NielsNet Avatar answered May 06 '26 22:05

NielsNet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!