This is best explained using an example. I need to reference the current class in a static method, this works as expected:
class Cls {
static fn<T extends typeof Cls>(
this: T,
arg: T extends typeof Cls ? true : false,
) {}
}
Cls.fn(true);
Cls.fn(false); // Argument of type 'false' is not assignable to parameter of type 'true'.
However, when calling Cls.fn from another static method, it doesn't work:
class Cls {
static fn1<T extends typeof Cls>(
this: T,
arg: T extends typeof Cls ? true : false,
) {}
static fn2<T extends typeof Cls>(this: T) {
this.fn1(true); // Argument of type 'true' is not assignable to parameter of type 'T extends typeof Cls ? true : false'.
}
}
Interestingly, it works if I remove fn2's generic or do this.fn1<typeof Cls>(true). This means the error is related to the type of this. I think it has to do with this referring to any subclass of Cls as opposed to exactly Cls. However, even if this is a subclass of Cls, T extends typeof Cls would still be true.
Is this a bug where Typescript uses the wrong value for this? If it's not a bug, how can I fix it?
In my actual code, I need to reference the current class because the method accepts different arguments depending on the subclass.