Angular 方法中的返回类值

Angular 方法中的返回类值,angular,typescript,Angular,Typescript,我想在Typescript中创建方法,它返回一个类值 例如: 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 我只想这样使用它: this.testObject.getData<getType('t

我想在Typescript中创建方法,它返回一个类值

例如:

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
我只想这样使用它:

this.testObject.getData<getType('test')>(filter :string);
this.backend.get(path)
    .map(results => myService.getData(path, results))
    .subscribe(...)
this.testObject.getData(过滤器:字符串);
这样的事情可能吗

其他例子:

 switch(Path){
    case '/testPath/':
      return this.categoryRepository.getAllData<ModelInterface1>(filter,Path);
    case '/testPath2/':
    return this.categoryRepository.getAllData<ModelInterface2>(filter,Path);
}
开关(路径){
案例“/testPath/”:
返回this.categoryRepository.getAllData(过滤器,路径);
案例“/testPath2/”:
返回this.categoryRepository.getAllData(过滤器,路径);
}

我想优化这个开关大小写构造。

Typescript中的泛型使用类型擦除,因此在运行时任何泛型参数都会丢失。您可以通过传递类构造函数来实现结果,因为它只是一个函数。这对接口不起作用,因为接口只是一个编译时构造,没有为其生成代码

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"))
编辑


在您的情况下,由于您使用一个接口调用一个方法,该接口无论如何都会在运行时被删除,因此您可以传递任何通用参数(满足
getAllData
的约束)。如果您对开关的分支不做任何操作,您可以只调用
this.categoryRepository.getAllData(过滤器,路径)
this.categoryRepository.getAllData(过滤器,路径);

您也许可以使用泛型执行类似的操作

// Classes/interfaces
class One {
    constructor(public name: string = 'one') {}
}
class Two {
    constructor(public num: number = 2) {}
}

// your service
class MyService {
    getData(path: string, rawData): One | Two {
        switch (path) {
            case 'one':
                return this.create<One>(One, rawData);
            case 'two':
                return this.create<Two>(Two, rawData);
            default:
                return rawData; // we don't know how to handle this
        }
    }
    // the generic method
    private create<T>(c: { new(...rest: any[]): T; }, data): T {
        return new c(...data);
    }
}

// your "json" data.
const oneData = 'something';
const twoData = 42;

// Usage
const service = new MyService();
const oneObj = service.getData('one', oneData);
console.log(oneObj);
const twoObj = service.getData('two', twoData);
console.log(twoObj);

这对我不起作用。接口只是REST-API中即将出现的数据的模型,我只知道在运行时GetData调用需要哪个接口。@Dennis你能添加一个完整的示例吗?我已经实现了这个问题。包含开关的函数返回什么?