reactjs - Typescript - 'string' no se puede asignar al tipo 'FC'
Estoy recibiendo el siguiente error:
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)
al usar la función de TypeScript a continuación, no entiendo el problema aquí, cualquier ayuda es apreciada, ¡gracias!
El código está abajo,
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 ;
Respuesta #1
Echa un vistazo al tipo 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;
}
Esta función devuelve ReactElement<any, any> | null.
Lo cual a su vez es solo un jsx con un conjunto de propiedades.
interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
type: T;
props: P;
key: Key | null;
}
Todo lo que necesitas hacer es envolver tu valor de retorno en un 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>
}
Intentemos usarlo sin 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} />
Por lo tanto, string simplemente no es JSX válido
Respuesta #2
Puedes envolver tu cadena en <Fragment>, y pasará la verificación de tipos.
El problema es que React espera un tipo ReactElement, y string no es uno de esos. Fragment te permite devolver strings y arrays a los componentes.
