首页 > 解决方案 > Typescript Vue:为方法使用动态字符串名称

问题描述

我的目标是根据变量值触发不同的函数。VS Code 给我一个错误警告,指出:

'method' implicitly has a type of 'any' because 'type1Func' and 'type1Func' are strings and can't be used as an index. 我在普通的 Vue js 文件上成功使用了类似的技术,但我不知道如何在这个打字稿文件中解决这个问题。

func handleListeningDevice(name: NewNameOption) {
  const method = !!name ? 'type1Func' : 'type2Func';
  
  this[method]({
    name: name ?? 'none',
  });
}

标签: typescriptvue.jsvuejs2

解决方案


首先欢迎。

每当我使用 TypeScript 时,我要记住的一件事是,你可以用 JS 做同样的事情(因为它是 JS,但有类型)它可以帮助我对 TS 保持冷静。

错误消息是说您不能string用作索引,这是因为在代码中this[method] 方法是索引,方法是字符串,但是正如您已经知道的那样,您可以按名称访问对象属性,换句话说,用字符串索引(所以代码将在纯 JS 中工作)

为了让它工作,您需要向 TS 提供更多信息,以便它停止抱怨。例如,您可以给它一个any类型 to method,这样您就告诉 TS 在运行时该类型将是可以使用的东西

 func handleListeningDevice(name: NewNameOption) {
  const method:any = !!name ? 'type1Func' : 'type2Func';

  this[method]({
   name: name ?? 'none',
  });
}

或者您也可以在使用方法时进行类型转换:

this[(method as any)]

或用于this指示字符串可以是索引的类型转换:

(this as {[key:string]:any})[method]

看看什么最适合你!


推荐阅读