I will start with overview of desired end result I'm trying to achieve:
class Dog {
public static withName(name: string) {
this.name = name;
}
constructor() {
//
}
//
}
class Cat {
public static withName(name: string) {
this.name = name;
}
constructor() {
//
}
//
}
function getAnimal(...) { ... }
let dog = getAnimal(Dog.withName('Rex'))
dog.bark();
dog.meow(); // TS Error: method 'meow' does not exist on type 'Dog'
let cat = getAnimal(Cat.withName('Fluffy'))
dog.meow();
dog.bark(); // TS Error: method 'bark' does not exist on type 'Cat'
Of course this is pretty much a simplified almost-pseudo-code.
So the idea is next: a function that accepts a class with called static method on it (in order to pre-setup some properties, e.g. withName).
Then this function returns an instance of this class with pre-setuped property.
function getAnimal(classWithStaticMethodCall: ???) {
return new classWithStaticMethodCall()
}
It's not a big deal to achieve something like this:
function foo(bar) {
return new bar()
}
But the thing is that I want TypeScript to somehow figure out WHAT EXACT CLASS I'm passing and not just return an instance of this class, but the instance of this class with pre-setuped property (with the help of static method withName()).
After trying different things I'm starting to thinking that this is not doable because I'm passing the method and not the class itself (Dog.withName() not Dog).
The thing is that I actually saw this API before and now I'm trying to replicate it.
To sum up:
let dog = getAnimal(Dog.withName('Lucky')) // Property name is now set on this exact dog
dog.bark();
dog.name // 'Lucky'