You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改对象键名?解决TypeScript类型索引报错问题

解决TypeScript对象键名映射时的类型错误

错误提示Element implicitly has an 'any' type because expression of type 'keyof SignInStore' can't be used to index type '{}'的核心原因是:reduce方法的初始值{}被TypeScript推断为空对象类型,而你用keyof SignInStore类型的键去索引这个空对象,TypeScript无法确认这些键在空对象上存在,因此抛出类型错误。

修改方案

给reduce的初始值指定Partial<SignInStore>类型(表示包含SignInStore部分属性的对象),最后将结果断言为SignInStore类型即可。同时优化default分支,避免非目标键的干扰:

interface SignInStore {
  storeId: number,
  storeName: string,
  email: string,
  destinationName: string,
  primaryPhone: string,
}
const signInStore = response.data;
// 给初始值指定Partial<SignInStore>类型
const parseSignInStore: SignInStore = Object.keys(signInStore).reduce((parseStore, param) => {
  let newParamName: keyof SignInStore | undefined;
  switch(param){
    case 'id':
      newParamName = 'storeId';
      break;
    case 'name':
      newParamName = 'storeName';
      break;
    case 'destination_name':
      newParamName = 'destinationName';
      break;
    case 'primary_phone':
      newParamName = 'primaryPhone';
      break;
    case 'email':
      newParamName = 'email';
      break;
    default:
      // 非目标键直接跳过,避免无效赋值
      return parseStore;
  }
  if (newParamName) {
    parseStore[newParamName] = signInStore[param];
  }
  return parseStore;
// 指定初始值类型为Partial<SignInStore>
}, {} as Partial<SignInStore>) as SignInStore; // 断言为完整的SignInStore类型

setSignInStore(parseSignInStore);
setIsSignedIn(true);

关键说明

  • Partial<SignInStore>允许对象只包含SignInStore的部分属性,符合reduce逐步构建对象的过程。
  • 最后用as SignInStore断言是因为你确保了所有SignInStore的属性都会被正确映射,TypeScript无法自动推断这一点,需要手动确认。
  • 优化default分支跳过非目标键,避免将无关属性混入结果对象。

内容的提问来源于stack exchange,提问作者Minwoo Jung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:27:39