如何解决打字稿中的隐式任何类型索引类型错误?

时间:2019-06-24 09:35:05

标签: typescript

如何解决此错误

  • “元素隐式具有'any'类型,因为类型'any'的表达式不能用于索引类型吗?“

此错误背后的原因是什么?什么是索引类型?代码在下面给出

const getPast = action => {
  const presentToPast = {
    approve: 'approved',
    reject: 'rejected',
    edit: 'edited',
    create: 'created'
  };

  return presentToPast[action];
};

2 个答案:

答案 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];
};