admin管理员组

文章数量:1405512

Imagine such code :

class Foo {
    foo(): string | number { return 3 }
}

class Bar extends Foo {
    foo(): number {
        return super.foo() as number;
    }
}

Would it be possible to just override the typing for the foo() method in Bar ?

Something like

class Bar extends Foo {
    override foo(): number;
}

So we don't have that unecessary super.foo() in the implementation.

Imagine such code :

class Foo {
    foo(): string | number { return 3 }
}

class Bar extends Foo {
    foo(): number {
        return super.foo() as number;
    }
}

Would it be possible to just override the typing for the foo() method in Bar ?

Something like

class Bar extends Foo {
    override foo(): number;
}

So we don't have that unecessary super.foo() in the implementation.

Share asked Mar 7 at 16:59 Matthieu RieglerMatthieu Riegler 56.9k27 gold badges148 silver badges200 bronze badges 1
  • Separate Bar interface to achieve declaration merging? class Bar extends Foo{}; interface Bar { foo(): number } – STerliakov Commented Mar 7 at 17:08
Add a comment  | 

1 Answer 1

Reset to default 1

There're several ways for example declare the method as an instance's prop or merge an interface. Not sure about consequences of the instance prop though, seems should be the same from the type POV.

Playground

class Foo {
    foo(): string | number { return 3 }
}

class Bar extends Foo {
    declare foo: () => number;    
}

interface Baz{
    foo(): number;
}

class Baz extends Foo {}

new Bar().foo
new Baz().foo

本文标签: typescriptTypeonly override on subclass methodStack Overflow