Vue/TypeScript:解决Type 'Ref<number>'无法作为索引类型的报错
解决Vue+TypeScript中
Ref<number>无法作为数组索引的问题 方法1:通过.value获取原始数值
ref()创建的响应式变量是包装对象,直接用对象本身作为数组索引会触发类型错误,必须通过.value访问内部的原始number值:
import { ref } from 'vue'; const refVariable = ref(0); const myArray = ['a', 'b', 'c']; // 正确写法 const targetItem = myArray[refVariable.value];
方法2:改用reactive定义索引变量
如果不需要单独的基础类型响应式变量,可以把索引放在reactive创建的对象中,直接访问属性就能得到原始数值类型:
import { reactive } from 'vue'; const state = reactive({ index: 0 }); const myArray = ['a', 'b', 'c']; // 直接访问属性即可 const targetItem = myArray[state.index];
方法3:类型断言(不推荐)
若明确refVariable的.value是合法索引,可通过类型断言绕过类型检查,但会丢失TypeScript的类型校验优势,仅在特殊场景使用:
const targetItem = myArray[refVariable as unknown as number];
内容的提问来源于stack exchange,提问作者tomysek
相关产品推荐
相关产品推荐

