[英]TypeScript and Vue class - TS7053 index signatures
Vue 2.6 with vue class component (and typescript).带有 vue class 组件(和打字稿)的 Vue 2.6。
Actual code:实际代码:
private validateField(fieldType: string, e: string) {
this[fieldType] = e.length > 0
}
Gives an error:给出一个错误:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Index'. TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“索引”。 No index signature with a parameter of type 'string' was found on type 'Index'.
在“索引”类型上找不到具有“字符串”类型参数的索引签名。
What's a recommended way to add signatures in my case?在我的案例中添加签名的推荐方法是什么?
What I would do is create an indexer interface:我要做的是创建一个索引器接口:
interface ILookup<T> {
[key: string]: T;
}
And then make the Vue class implement this interface:然后让Vue class实现这个接口:
export default class App extends Vue implements ILookup<any> {
[index: string]: any;
private validateField(fieldType: string, e: string) {
this[fieldType] = e.length > 0
}
}
We have to use an any
as type parameter because Vue internally uses all kinds of different types which can be indexed on you component object.我们必须使用
any
作为类型参数,因为 Vue 内部使用各种不同的类型,这些类型可以在您的组件 object 上进行索引。 So for example when we use a boolean
as type parameter:例如,当我们使用
boolean
作为类型参数时:
interface ILookup<T> {
[key: string]: T;
}
export default class App extends Vue implements ILookup<boolean> {
[index: string]: boolean;
private validateField(fieldType: string, e: string) {
this[fieldType] = e.length > 0
}
}
we get the following (and other) compilation errors:我们得到以下(和其他)编译错误:
TS2411: Property '$attrs' of type 'Record' is not assignable to string index type 'boolean'.
TS2411:“记录”类型的属性“$attrs”不可分配给字符串索引类型“布尔”。
and:和:
TS2411: Property '$children' of type 'Vue[]' is not assignable to string index type 'boolean'.
TS2411:“Vue []”类型的属性“$children”不可分配给字符串索引类型“布尔”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.