动态返回基于字符串的类型

时间:2017-10-24 11:14:50

标签: typescript

是否可以将字符串传递给函数并分配返回的动态类型?

class MyService {
  aMethod(arg) {
    console.log(arg)
  }
}

Container.register('my_service', MyService);

// Internally Container holds a Object 
export interface IServiceInstance {
    name: string;
    type: Function;
    instance: Object;
}

const myServiceInstance = Container.get('my_service')

// myServiceInstance should be detected as type of MyService class
myServiceInstance.aMethod('Hello World') 

// Currently I use it like this. But if it is possible I want to get rid of that
const myServiceInstance = (Container.get('my_service') as MyService)

1 个答案:

答案 0 :(得分:1)

您可以扩展容器的类型,以按字符串常量添加方法特化:

// In a library for example
declare class ContainerClass {
    register<T>(name: string, ctor: new ()=> T): void;
    get (name: string) : any;
}
let Container: ContainerClass ;


// In your app
class MyService {
    aMethod(arg) {
      console.log(arg)
    }
  }

Container.register('my_service', MyService);
interface ContainerClass {
    get (name: 'my_service') : MyService;
}
Container.get('my_service').aMethod("");

这利用了可以通过在同一名称空间中声明具有相同名称的接口来扩展类型(接口或类)的事实。