Ts中 string、number和any等类型 不能当作索引用,怎么处理?

先看错误信息

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>

  • 11
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值