TypeScript扩展DefaultTheme的colors属性出现never类型错误如何解决
错误根因
出现Type string is not assignable to type 'never'报错的核心原因有两个:
- 交叉类型的源类型选择错误:你写的
DefaultTheme & { background: '#06090D' }是将完整的DefaultTheme接口(包含顶级的colors、pages属性)和带background的对象交叉,没有正确取到DefaultTheme下的colors属性结构 - 同名字面量类型互斥:即使修正为取
DefaultTheme['colors']和新background交叉,原有colors里的background是字面量类型'#fff',和新的字面量'#06090D'互斥,两个无法同时满足的类型交叉结果就是never
解决方案
调整PageTheme的类型定义,先通过Omit移除原有background属性,再追加新的background类型即可:
export interface PageTheme { sensei: { colors: Omit<DefaultTheme['colors'], 'background'> & { background: '#06090D' } } }
修改后你原有的主题对象合并代码不需要改动,展开defaultTheme.colors后重写background的逻辑可以正常执行,同时colors下的text、secondaryText、primary属性会保留DefaultTheme的原有类型约束,符合你只重写background的需求。
内容的提问来源于stack exchange,提问作者Darkbound
相关产品推荐
相关产品推荐

