TypeScript报错:'number | undefined'无法赋值给类型'string'的解决方法
解决FlipNumbers组件TypeScript类型不匹配问题
下面是几种可行的解决方法,适配visitor?.count(类型number | undefined)转成组件要求的string类型:
方法1:空值合并+模板字符串转换
用模板字符串把数字转成字符串,同时通过空值合并运算符??处理undefined的情况,给一个默认值(比如"0"):
<FlipNumbers height={12} width={12} color="white" background="red" play perspective={100} numbers={`${visitor?.count ?? 0}`} />
方法2:toString()结合可选链+空值合并
先通过可选链确保count存在时调用toString()转成字符串,不存在则用默认字符串:
<FlipNumbers height={12} width={12} color="white" background="red" play perspective={100} numbers={visitor?.count?.toString() ?? "0"} />
方法3:条件渲染组件(如果不希望显示默认值)
如果visitor?.count不存在时不想渲染组件,可以加条件判断:
{visitor?.count !== undefined && ( <FlipNumbers height={12} width={12} color="white" background="red" play perspective={100} numbers={String(visitor.count)} /> )}
关键说明
??运算符只会在左侧值为null或undefined时返回右侧默认值,避免了0被误替换的问题- 模板字符串、
String()、toString()都能把数字类型安全转成字符串类型,满足组件的类型要求
内容的提问来源于stack exchange,提问作者Esther
相关产品推荐
相关产品推荐

