Answer the question
In order to leave comments, you need to log in
How to return a specific method type through a proxy function?
I have a set of classes, from one parent. All methods return the same types, for each method.
There is a f-tsya driver which, according to some logic, decides from which class to call the method passed in the argument.
As a result, driver returns a mix of types to call any argument.
The question is how to show ts that by passing the `getString` argument - I want to get the type string in the stringResult variable
interface ParentI {
getString: () => string;
getNumber: () => number;
getBoolean: () => boolean;
}
class Parent implements ParentI {
getString() {
return 'test';
}
getNumber() {
return 2;
}
getBoolean() {
return true;
}
}
class ChildrenA extends Parent {
getString() {
return 'first';
}
getNumber() {
return 2;
}
}
class ChildrenB extends Parent {
getString() {
return 'second';
}
getNumber() {
return 2;
}
}
type R = keyof ParentI;
class Driver {
childrenA = new ChildrenA();
childrenB = new ChildrenB();
resolveMethod(methodName: R) {
const random = Math.random();
if (random > 0.5) {
return this.childrenA[methodName]();
} else {
this.childrenB[methodName]();
}
}
}
const driver = new Driver();
const stringResult = driver.resolveMethod('getString'); // тут возвращается (string | number | boolean) - надо только (string)
const numberResult = driver.resolveMethod('getNumber'); // тут возвращается (string | number | boolean) - надо только (number)
const BooleanResult = driver.resolveMethod('getBoolean'); // тут возвращается (string | number | boolean) - надо только (boolean)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question