Typescript - 字符串'不可分配给类型'FC

7
我遇到了以下错误:
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  ;

如果您想嵌入代码,请使用三个反引号。请参阅我在答案中的操作。 - captain-yossarian from Ukraine
2个回答

4

看一下 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;
    }


你只需要将返回值包装在标签中即可:
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。

4
你可以将字符串包装在<Fragment>中,这样它就会通过类型检查。
问题在于React期望的是ReactElement类型,而string不是其中之一。Fragment允许你向组件返回字符串和数组。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接