I would like to create method in Typescript, which returns a classvalue.
For Example:
getType(value :string){
switch(value){
case 'test':
return ExampleInterface.class //or .type or something like this
//... Can go on with more cases and other returnvalues
And I just want to use it like this:
this.testObject.getData<getType('test')>(filter :string);
Is something like this possible?
Other Example :
switch(Path){
case '/testPath/':
return this.categoryRepository.getAllData<ModelInterface1>(filter,Path);
case '/testPath2/':
return this.categoryRepository.getAllData<ModelInterface2>(filter,Path);
}
I would like to optimize this switch-case construct.
Generics in Typescript use type erasure, so at runtime any generic argument is lost. You can achieve the result by passing the class constructor around as it is just a function. This will not work for interfaces, as interfaces are just a compile time construct and have no code generated for them.
interface AllResults{}
class ExampleClass implements AllResults { }
function getType(value: string): new () => AllResults {
switch (value) {
case 'test':
return ExampleClass
}
throw new Error();
}
function createInstance(ctor: new () => AllResults): AllResults {
return new ctor();
}
createInstance(getType("test"))
Edit
In your case, since you call a method with an interface, which will be erased at runtime anyway, you can pass any generic parameter (that satisfies the constraints of getAllData. If you do nothing on the branches of the switch, you can just call this.categoryRepository.getAllData<any>(filter,Path); or this.categoryRepository.getAllData<IBaseModelInterface>(filter,Path);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With