TypeScript报错咨询:'GetAmountProps'无法赋值给'string'类型
错误原因解析
- 参数类型声明错误:你给
getAmount函数的参数标注了GetAmountProps类型,这是一个包含value属性的对象,但函数内部却把这个参数当成单独的字符串/undefined值来处理(比如判断value === undefined),逻辑和类型定义完全不匹配。 - 返回值类型不兼容:函数声明的返回值是
string类型,但最后你返回的是整个GetAmountProps对象,对象类型无法赋值给string类型,因此触发了类型错误。
两种修正方案:
- 保留接口,函数接收对象参数,访问对象的
value属性:
interface GetAmountProps { value: undefined | string } const getAmount = (props: GetAmountProps): string => { if (props.value === undefined) return '(0)'; return props.value; }; export default getAmount;
- 去掉接口,让函数直接接收字符串/undefined类型的参数:
const getAmount = (value: undefined | string): string => { if (value === undefined) return '(0)'; return value; }; export default getAmount;
内容的提问来源于stack exchange,提问作者Дмитрий Сухоцкий
相关产品推荐
相关产品推荐

