先看错误信息
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: string; b: string; }'.
No index signature with a parameter of type 'string' was found on type '{ a: string; b: string; }'.Vetur(7053)元素隐式具有 "any" 类型,因为类型为 "string" 的表达式不能用于索引类型 "{ a: string; b: string; }"。
在类型 "{ a: string; b: string; }" 上找不到具有类型为 "string" 的参数的索引签名。ts(7053)
ts代码
const test1 = {
a:"小帅",
b:"小美"
}
const fn1 = (type:string) =>{
const protagonist = test1[type] // 报错
console.log("我是:%s",protagonist);
}
这里以 string 类型的索引为例,number 同理。
解决方法
方案一:(不推荐)
const fn1 = (type:string) =>{
const protagonist = (test1 as any)[type];
console.log("我是:%s",protagonist);
}
方案二:
const fn1 = (type:string) =>{
const protagonist = test1 [type as keyof typeof test1]
console.log("我是:%s",protagonist);
}
方案三:
const fn1 = function <T extends object, K extends keyof T>(test1: T, type: K) { // 注:此时有两个参数
const protagonist = test1[type];
console.log("我是:%s",protagonist);
}
方案四:
<script setup lang='ts'>
enum testType {
"松鼠" = "a",
"小白" = "b",
}
const test2 = {
[testType["松鼠"]]:()=>{console.log("A")},
[testType["小白"]]:()=>{console.log("B")}
}
const fn2 = (type:testType) =>{
test2[type]()
}
</script>
<template>
<button @click="fn2(testType['松鼠'])">打印A</button>
<button @click="fn2(testType['小白'])">打印B</button>
</template>