Is it possible to name the currently class's instance type within a static method in a base class?
In other words, can you ensure type checking in the following code:
class Base {
static addInitializer(i: (v: any /* What type would go here? */) => void) {
// implementation is irrelevent
}
}
class Dog extends Base {
bark() {}
}
class Fish extends Base {
swim() {}
}
Dog.addInitializer((dog) => {
dog.bark();
// @ts-expect-error
dog.swim();
});
Fish.addInitializer((fish) => {
fish.swim();
// @ts-expect-error
fish.bark();
});
Note the use of // @ts-expect-error
before lines that should be a type error. This is due to the fact that v
has type any
rather than the desired named type.
TypeScript playground link