No index signature with a parameter(索引签名)

本文介绍了TypeScript中索引签名的概念及其在接口定义中的应用。通过示例展示了如何使用索引签名解决‘Noindexsignaturewithaparameteroftype'string'wasfoundontype'IStatusType’的错误。同时,解释了索引签名的作用,即定义对象中属性名和属性值的类型,确保类型安全。此外,还探讨了有限的字符串字面量在索引签名中的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.索引签名:No index signature with a parameter

No index signature with a parameter of type 'string' was found on type 'IStatusType'

解释:没有在类型 "IStatusType” 上找到参数类型为"string"的索引签名

  • 报错设定
// 返回值状态
interface IStatusType{
    400:string,
    401:string,
    403:string,
    404:string,
    405:string,
    500:string,
    502:string,
}
// 定义参数
const _status:IStatusType= {
    400:"请求错误",
    401:"登录已过期,请重新登录",
    403:"禁止访问",
    404:"接口不存在",
    405:"资源被禁止",
    500:"内部服务器错误",
    502:"网关错误"
}
// 返回结果例:err.response.data.status  === 400
 const errStatus:string = err.response.data.status;
/*报错:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IStatusType'.
  No index signature with a parameter of type 'string' was found on type 'IStatusType'
*/
 console.log(_status![errStatus]);
  • 解决方案:
    修改IStatusType类型设定 就不会报错了
 interface IStatusType{
    [key: string ]: string;
}

2.什么是索引签名

简单来说:它定义了对象中属性名、属性值的类型
tip:TypeScript 的索引签名必须是 string 或者 number

interface Foo {
  [key: string]: number;
  x: number;
  y: number;
}

或者

索引签名的名称(如:{ [index: string]: { message: string } } 里的 index )除了可读性外,并没有任何意义。例如:如果有一个用户名,你可以使用 { username: string}: { message: string },这有利于下一个开发者理解你的代码

const foo: {
  [index: string]: { message: string };
} = {};

// 储存的东西必须符合结构
// ok
foo['a'] = { message: 'some message' };
  • 有限的字符串字面量

通常与 keyof/typeof 一起使用,来获取变量的类型

type Index = 'a' | 'b' | 'c';
type FromIndex = { [k in Index]?: number };
const good: FromIndex = { b: 1, c: 2 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值