我在格式化此API数据时出错,奇怪的是它是控制台记录我想要的响应,并且格式是数字。
有人知道为什么打字稿不接受这个问题以及什么可能导致这个问题吗?
代码
import React, { useEffect, useState } from 'react';
import api from '../../services';
import { CardsList, Value } from './styles';
interface ContractProps {
data: {
dataCards: {
billing: {
monthlyBilling: number;
};
}
}
}
const Cards: React.FC = () => {
const [contract, setContract] = useState<ContractProps>();
const monthlyBillingData = contract?.data.dataCards.billing.monthlyBilling;
useEffect(() => {
api.get('').then(response => {
setContract(response.data);
});
}, []);
console.log(monthlyBillingData);
console.log(typeof(monthlyBillingData));
console.log(new Intl.NumberFormat().format(monthlyBillingData));
return (
<CardsList>
<h3>Ativos</h3>
<Value>
<strong>R$ {contract?.data.dataCards.billing.monthlyBilling}</strong>
</Value>
</CardsList>
);
};
export default Cards;
错误
No overload matches this call.
Overload 1 of 2, '(value: number | bigint): string', gave the following error.
Argument of type 'number | undefined' is not assignable to parameter of type 'number | bigint'.
Type 'undefined' is not assignable to type 'number | bigint'.
Overload 2 of 2, '(value: number): string', gave the following error.
Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'. TS2769
28 | console.log(monthlyBillingData);
29 | console.log(typeof(monthlyBillingData));
> 30 | console.log(new Intl.NumberFormat().format(monthlyBillingData));
| ^
31 |
32 |
33 | return (
console.<computed> @ index.js:1
handleErrors @ webpackHotDevClient.js:174
push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @ webpackHotDevClient.js:213
index.tsx:28 100000
index.tsx:29 number
index.tsx:30 100,000
答案 0 :(得分:0)
如果?.
为空,这里的可选链接(undefined
)运算符将给出contract
:
contract?.data.dataCards.billing.monthlyBilling
^
在这种情况下,您需要以类型安全的方式决定要呈现的内容和/或要登录的内容。这取决于您希望实现的逻辑。
请注意,
new Intl.NumberFormat().format(undefined)
返回字符串"NaN"
,该字符串不太可能有用(在TypeScript认为它不是您想要的范围内)。