用字符串名称调用Typescript对象函数

时间:2019-03-24 00:43:57

标签: angular typescript

我班上有多项服务。这些函数的名称以字符串数组形式出现,我试图将它们分别调用而没有太大的成功。

cars.forEach( car => {
    this.carService[ car.name ](
        height,
        plateNr
    );
} );

此版本出现错误:

ERROR TypeError: _this.carService[car.name] is not a function

如果我尝试使用模板文字(this.carService [`$ {car.name}`]):

ERROR TypeError: _this.carService[("" + car.name)] is not a function

如果我直接输入单个函数名称,它将起作用。

this.carService[ 'Honda' ] //好的

谢谢。

2 个答案:

答案 0 :(得分:0)

如果将carService定义为对象文字,则它将缺少索引签名(即,作为任意字符串查找结果使用的内容)。 TypeScript不知道您的键在对象的上下文中有特殊的含义,因此很可能无法推断查找结果可能是一个函数。

当我在本地做类似的事情时,我却没有得到同样的抱怨:

        const a = { b: () => {}, c: () => {}};
        const x = ["b", "c"];
        x.forEach(functionName => (a[functionName])());

我得到的抱怨是:“元素隐式具有'any'类型,因为类型'{b:()=> void; c:()=>无效; }'没有索引签名。”

有两种解决方法:

  1. 将您的服务定义为具有索引签名的字典:
        const a: { [functionName: string]: Function } = { b: () => {}, c: () => {}};
        const x = ["b", "c"];
        x.forEach(functionName => (a[functionName])());
  1. 将传入的键列表明确定义为对象的有效键:
        const a = { b: () => {}, c: () => {}};
        const x = ["b", "c"] as (keyof typeof a)[];
        x.forEach(functionName => (a[functionName])());

哪个更可取取决于您要使用服务和密钥列表的确切程度。

答案 1 :(得分:0)

尝试正常工作

cars.forEach( car =>
     { 
let carName = car.name;
    this.carService[ carName ]( height, plateNr ); 
} );