Typescript bindings for classes with methods that shadow a parent's methods with different signatures

与世无争的帅哥 提交于 2019-12-13 02:46:19

问题


I'm working on ts-for-gjs. It generates typescript definitions for gjs, which lets you use gobject-introspection libraries, such as Gtk and GStreamer, in a JS runtime (based on Spidermonkey).

Many of the introspected classes have pseudo-constructors as static methods, which leads to some of them having one or more static methods with the same names as methods in their parent classes but with different signatures.

Experimenting with ways to solve this problem I found that, if I wanted this API:

export class Parent {
    ...
    static new(arg1: string): Parent
}

export class Child extends Parent {
    ...
    static new(arg1: number, arg2: number): Child
}

all I have to do is add this to Parent:

static new<T, V>(arg1: T): V

This also works if Parent.new takes more arguments than Child.new instead of the other way round shown here.

What I'm puzzled by is why does this work when the generic form only has one argument, but one of the overloads takes two? I was expecting to have to write it something like:

static new<T, V>(arg1: T, arg2?: number): V

but the compiler accepts it without that arg2, and the compiled code works as desired and expected. I'm not complaining that it does, but I would like to understand it even though it works in my favour. This is basically my question, why is arg2 not required?

For anyone curious about the generic return type V, I found a good reason to use that instead of, say, Child | Parent, which is explained at the end of this comment.

来源:https://stackoverflow.com/questions/56992314/typescript-bindings-for-classes-with-methods-that-shadow-a-parents-methods-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!