javascript - TypeScript 和 Vue 类 - TS7053 索引签名

标签 javascript typescript vue.js

带有 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/

相关文章:

javascript - 通过 AJAX 重新加载下拉菜单中提交的 PHP 变量

javascript - 我如何通过 Google Analytics 在我的网站上跟踪 Facebook?

javascript - 在 D3 树中添加鼠标悬停时的文本

typescript - 柯里化(Currying)函数的返回类型

javascript - 将jquery库函数写入typescript

javascript - Vue动态计算输入变化

javascript - 如何向简单的 html 画廊添加标题

visual-studio - 在 Visual Studio 中为 typescript 生成文档注释

javascript - 如何使用 Vue.js @mouseover 将 <svg> 中的 <path> 作为目标?

javascript - 将 Alpine.js x-transitions 转换为 Vue.js 转换类?