打字稿 - 字符串"不能分配给类型"FC



我得到下面的错误:

Type '(props: PropsWithChildren<{ amount: number; }>) => string' is not assignable to type 'FC<{ amount: number; }>'.
Type 'string' is not assignable to type 'ReactElement<any, any> | null'.ts(2322)

在使用下面的typescript函数时,不理解这里的问题,任何帮助都是感激的,谢谢!

代码如下,

const MoneyAmount: React.FC<{amount : number}> = (props) => {
return (
new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD", 
maximumFractionDigits: 4
}).format(props.amount))
}
export default MoneyAmount  ;

看看FC类型:

type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}

这个函数返回ReactElement<any, any> | null

这反过来只是一个具有一组属性的jsx

interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
type: T;
props: P;
key: Key | null;
}

您所需要做的就是将返回值包装成span:

const MoneyAmount: React.FC<{ amount: number }> = (props) => {
const text = new Intl.NumberFormat("en-US", {
style: "currency", currency: "USD", maximumFractionDigits: 4
})
.format(props.amount)

return <span>{text}</span>
}

让我们试着不使用FC:

import React from 'react'
const MoneyAmount = (props: { amount: number }) => {
return (
new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 4
}).format(props.amount))
}
// Its return type 'string' is not a valid JSX element.
const x = <MoneyAmount amount={42} />

因此,string只是无效的JSX

你可以用<Fragment>来包装你的字符串,它会通过typecheck。

问题是React期望ReactElement类型,而string不是其中之一。Fragment允许您将字符串和数组返回给组件。

最新更新