Home > Blockchain >  extended class has different type than base, supported by interface
extended class has different type than base, supported by interface

Time:10-28

Can I write a method which is an extension of a base class, but with a different return type, if it's supported by the shared interface, without inserting type declaration in class 'a'?

In practice classes a & b are in javascript files, and they're failing lint-ts-typing checks.

typescript definition file

interface x {
    abc(): string | number;
}

javascript file


class a implements x {
    abc() {
        return 234;
    }
}

class b extends a implements x {
    abc() {
        return '123';
    }
}

throws the following: Property 'abc' in type 'b' is not assignable to the same property in base type 'a'. Type '() => string' is not assignable to type '() => number'. Type 'string' is not assignable to type 'number'.

playground link

CodePudding user response:

TS doesn't force you to implement the interface exactly
You are implementing is as

class a implements x {
    abc(): number {
        return 234;
    }
}

If you want to keep the number | string type, you have to do id expliticly:

class a implements x {
    abc(): number | string {
        return 234;
    }
}

CodePudding user response:

In your class a, you have to specify the return type of abc(). Otherwise it will assume that it only returns number value. Below code will resolve your error -

interface x {
    abc(): string | number;
}

class a implements x {
    abc(): string | number {
        return 234;
    }
}

class b extends a implements x {
    abc() {
        return '123';
    }
}
  • Related