typescript - Type-only override on subclass method - Stack Overflow

Imagine such code :class Foo {foo(): string | number { return 3 }}class Bar extends Foo {foo(): numbe

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744916956a4600894.html

相关推荐

  • typescript - Type-only override on subclass method - Stack Overflow

    Imagine such code :class Foo {foo(): string | number { return 3 }}class Bar extends Foo {foo(): numbe

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信