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.