TypeScript遍历对象时如何正确给key声明类型解决ts(2345)报错
报错原因
Object.entries原生类型定义返回的键是通用string类型,无法自动匹配你定义的TLocaleKey窄类型- TS 语法限制不允许直接在
for...of循环的左值位置加类型注解
可行解决方案
方案1:调用时直接断言(改动最小)
在使用key的位置直接做类型断言即可:
export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => { for (const [key] of Object.entries(initialData)) { if (!fields.includes(key as TLocaleKey)) { delete initialData[key] } } return initialData }
方案2:整体断言Object.entries返回值
如果你希望解构出来的key天然就是TLocaleKey类型,可以直接断言entries的返回类型:
export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => { for (const [key] of Object.entries(initialData) as Array<[TLocaleKey, unknown]>) { if (!fields.includes(key)) { delete initialData[key] } } return initialData }
方案3:类型守卫(运行时安全)
如果需要在运行时也校验key的合法性,避免类型断言带来的安全隐患,可以加一层类型守卫:
// 先定义类型守卫,需要你填入所有合法TLocaleKey的枚举/数组 const ALL_VALID_LOCALE_KEYS: TLocaleKey[] = [] function isLocaleKey(key: string): key is TLocaleKey { return ALL_VALID_LOCALE_KEYS.includes(key as TLocaleKey) } export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => { for (const [key] of Object.entries(initialData)) { if (!isLocaleKey(key) || !fields.includes(key)) { delete initialData[key] } } return initialData }
额外优化建议
你当前的实现直接修改了入参initialData,会污染原始的API响应对象,建议先浅拷贝再操作:
export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => { // 浅拷贝避免修改原对象 const processedData = {...initialData} for (const [key] of Object.entries(processedData) as Array<[TLocaleKey, unknown]>) { if (!fields.includes(key)) { delete processedData[key] } } return processedData }
内容的提问来源于stack exchange,提问作者user16754275
相关产品推荐
相关产品推荐

