如何解决此错误
此错误背后的原因是什么?什么是索引类型?代码在下面给出
const getPast = action => {
const presentToPast = {
approve: 'approved',
reject: 'rejected',
edit: 'edited',
create: 'created'
};
return presentToPast[action];
};
答案 0 :(得分:0)
欢迎使用Sayan stackoverflow
代码上的问题是您使用的是未键入的参数(操作),您可以尝试:
const getPast = ( action: string ) => {
const presentToPast = {
approve: 'approved',
reject: 'rejected',
edit: 'edited',
create: 'created'
};
return presentToPast[action];
};
console.log(getPast('approve'));// gonna log : approved
答案 1 :(得分:0)
我会为presentToPast创建自定义类型
type presentToPastType = {
approve: 'approved',
reject: 'rejected',
edit: 'edited',
create: 'created',
};
const getPast = (action: keyof presentToPastType) => {
const presentToPast = {
approve: 'approved',
reject: 'rejected',
edit: 'edited',
create: 'created',
};
return presentToPast[action];
};
或解决方法将是
const getPast = (action: keyof typeof presentToPast) => {
const presentToPast = {
approve: 'approved',
reject: 'rejected',
edit: 'edited',
create: 'created',
};
return presentToPast[action];
};