Array.reduce中Type 'string'不可赋值给'type never'错误的解决方法
解决TypeScript中Array.reduce创建键值相同对象的类型错误
错误原因
你遇到的Type 'string' is not assignable to type 'never'错误,本质是因为给reduce的初始值断言成了WeatherKeyMap——这个类型要求所有WeatherKeys对应的属性必须存在,但初始空对象{}完全不满足该要求,TypeScript因此把空对象的属性类型推断为never,赋值时自然出现类型不匹配的报错。
解决方案
方法1:用Partial调整初始值类型
把初始值的类型改成Partial<WeatherKeyMap>(让所有属性变为可选),遍历完成后再断言回完整的WeatherKeyMap(我们明确会遍历所有键,最终对象会包含所有必填属性):
const weather = { sunny: '맑음', partlyCloudy: '구름 조금', mostlyCloudy: '구름 많음', cloudy: '흐림', rain: '비', snow: '눈', rainOrSnow: '비 또는 눈', snowOrRain: '눈 또는 비', thunderstorm: '천둥번개', fog: '안개', yellowDust: '황사' }; type WeatherKeys = keyof typeof weather; type WeatherKeyMap = { [K in WeatherKeys]: K }; const foodKeys = (Object.keys(weather) as WeatherKeys[]).reduce((acc, key) => { acc[key] = key; return acc; }, {} as Partial<WeatherKeyMap>) as WeatherKeyMap;
方法2:用Object.fromEntries替代reduce
如果不需要用reduce,可以用更简洁的Object.fromEntries实现,类型处理更直观:
const foodKeys = Object.fromEntries( (Object.keys(weather) as WeatherKeys[]).map(key => [key, key]) ) as WeatherKeyMap;
这种方式直接把键值对数组转换成对象,再通过类型断言指定最终类型,避免了reduce过程中的类型冲突问题。
内容的提问来源于stack exchange,提问作者Yookyoung.Park
相关产品推荐
相关产品推荐

