带有 vue 类组件(和 typescript )的 Vue 2.6。
实际代码:
private validateField(fieldType: string, e: string) {
this[fieldType] = e.length > 0
}
报错:
TS7053:元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Index”类型。 在“Index”类型上找不到带有“string”类型参数的索引签名。
在我的案例中添加签名的推荐方法是什么?
最佳答案
我要做的是创建一个索引器界面:
interface ILookup<T> {
[key: string]: T;
}
然后让Vue类实现这个接口(interface):
export default class App extends Vue implements ILookup<any> {
[index: string]: any;
private validateField(fieldType: string, e: string) {
this[fieldType] = e.length > 0
}
}
我们必须使用 any
作为类型参数,因为 Vue 内部使用各种不同的类型,这些类型可以在组件对象上建立索引。例如,当我们使用 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
}
}
我们收到以下(和其他)编译错误:
TS2411: Property '$attrs' of type 'Record' is not assignable to string index type 'boolean'.
和:
TS2411: Property '$children' of type 'Vue[]' is not assignable to string index type 'boolean'.
关于javascript - TypeScript 和 Vue 类 - TS7053 索引签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58547073/