如何修改对象键名?解决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
相关产品推荐
相关产品推荐

