TypeScript 索引签名
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 };