Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript Vue:为方法使用动态字符串名称_Typescript_Vue.js_Vuejs2 - Fatal编程技术网

Typescript Vue:为方法使用动态字符串名称

Typescript Vue:为方法使用动态字符串名称,typescript,vue.js,vuejs2,Typescript,Vue.js,Vuejs2,我的目标是根据变量值触发不同的函数。VS代码向我发出错误警告,指出: “method”隐式具有“any”类型,因为“type1Func”和“type1Func”是字符串,不能用作索引。我在一个普通的Vue js文件上成功地使用了类似的技术,但我不知道如何在这个typescript文件中解决这个问题 func handleListeningDevice(name: NewNameOption) { const method = !!name ? 'type1Func' : 'type2Func

我的目标是根据变量值触发不同的函数。VS代码向我发出错误警告,指出:

“method”隐式具有“any”类型,因为“type1Func”和“type1Func”是字符串,不能用作索引。我在一个普通的Vue js文件上成功地使用了类似的技术,但我不知道如何在这个typescript文件中解决这个问题

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

每当我使用TypeScript时,我都会记住一件事,那就是你可以用JS做同样的事情(因为它是JS,但是用类型),这有助于我在使用TS时保持冷静

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

为了让它工作,你需要给TS更多的信息,这样它就不会抱怨了。例如,您可以将
any
类型指定给
method
,告诉TS在运行时可以使用该类型

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

  this[method]({
   name: name ?? 'none',
  });
}
或者,您也可以在使用方法时执行类型转换:

this[(method as any)]
或对该
进行类型转换,以指示字符串可以作为索引:

(this as {[key:string]:any})[method]
看看什么最适合你