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

npc*_*ete 7 typescript reactjs

我收到以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

当使用下面的打字稿功能时,不理解这里的问题,感谢任何帮助,谢谢!

代码如下,

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)
Run Code Online (Sandbox Code Playgroud)

cap*_*ian 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;
    }
Run Code Online (Sandbox Code Playgroud)

该函数返回ReactElement<any, any> | null.

这又只是一jsx组属性。

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

Run Code Online (Sandbox Code Playgroud)

您需要做的就是将返回值包装到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>
}
Run Code Online (Sandbox Code Playgroud)

让我们尝试在不使用它的情况下使用它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} />
Run Code Online (Sandbox Code Playgroud)

因此,string只是无效的 JSX