typescript - 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',
});
}
解决方案
首先欢迎。
每当我使用 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]
看看什么最适合你!
推荐阅读
- go - golang 的手册页?
- javascript - 如何确定用户是否在 Javascript 中附加了键盘
- java - 使用 TomEE 嵌入式和 Microprofile 容错进行集成测试
- javafx - JavaFX按钮背景向右溢出1px
- php - Sql CURDATE() 下个月不工作
- ios - 从 DynamoDB 中的表中获取信息
- r - 创建表达式测试以查看 R 中的 `as.formula('X ~ 1')` 是否包含截距?
- java - 对两个没有任何关系的不同表使用 CriteriaQuery
- assembly - 可以获得 Keypress 并打印它的组装操作系统
- android - layout_collapseMode:PIN 不起作用