在TypeScript中使用styled-components条件Props时遇逻辑&&报错
styled-components中使用&&运算符触发TypeScript错误的解决方案
问题原因
你的selected是可选布尔属性(selected?: boolean),当selected为undefined或false时,selected && hoverfragment会返回undefined或false,而styled-components的插值类型不接受这两种值,仅允许有效的样式片段、null、空字符串('')等合法类型。这就是用&&报错,但三元运算符?:能正常工作的原因——三元运算符可以明确返回合法的空值替代undefined/false。
解决办法
方法1:使用三元运算符返回合法空值
直接替换&&为三元运算符,明确指定selected为假值时返回空字符串或null:
const container = styled.div<ContainerProps>` display: flex; flex-direction: row; justify-content: space-between; ${({ selected }) => selected ? hoverfragment : ''} `;
方法2:给props设置默认值并确保返回合法值
解构selected时设置默认值为false,再用三元运算符返回有效内容:
const container = styled.div<ContainerProps>` display: flex; flex-direction: row; justify-content: space-between; ${({ selected = false }) => selected ? hoverfragment : ''} `;
内容的提问来源于stack exchange,提问作者TechDan
相关产品推荐
相关产品推荐

