2

I saw this example in the docs:

<FormattedMessage
  id="foo"
  defaultMessage="To buy a shoe, <a>visit our website</a> and <cta>buy a shoe</cta>"
  values={{
    a: chunks => (
      <a
        class="external_link"
        target="_blank"
        href="https://www.example.com/shoe"
      >
        {chunks}
      </a>
    ),
    cta: chunks => <strong class="important">{chunks}</strong>,
  }}
/>

but when using typescript, the following error occurs for the chunks functions:

No overload matches this call.
  Overload 2 of 2, '(props: Props, context: any): FormattedMessage', gave the following error.
    Type '(chunks: any) => Element' is not assignable to type 'string | number | boolean | Element | Date | null | undefined'.
      Type '(chunks: any) => Element' is not assignable to type 'Date'.
  Overload 2 of 2, '(props: Props, context: any): FormattedMessage', gave the following error.
    Type '(chunks: any) => Element' is not assignable to type 'string | number | boolean | Element | Date | null | undefined'.
      Type '(chunks: any) => Element' is not assignable to type 'Date'.

Is the types for FormattedMessage not accepting functions?

Gregory
  • 149
  • 1
  • 10

2 Answers2

2

Type string[] will work without any errors.

<FormattedMessage
    id="foo"
    defaultMessage="To buy a shoe, <a>visit our website</a> and <cta>buy a shoe</cta>"
    values={{
      a: (chunks: string[]) => (
        <a
          className="external_link"
          target="_blank"
          rel="noreferrer"
          href="https://www.example.com/shoe"
        >
          {chunks}
        </a>
      ),
      cta: (chunks: string[]) => (
        <strong className="important">{chunks}</strong>
      )
    }}
  />
Jason Jin
  • 1,739
  • 14
  • 21
0

string[] didn't work for me but ReactNode[] did. But I had to upgrade to react-intl v6.4.2. (Both string[] and ReactNode[] failed for me on react-intl v5.)

<FormattedMessage
    id="foo"
    defaultMessage="To buy a shoe, <a>visit our website</a> and <cta>buy a shoe</cta>"
    values={{
      a: (chunks: ReactNode[]) => (
        <a
          className="external_link"
          target="_blank"
          rel="noreferrer"
          href="https://www.example.com/shoe"
        >
          {chunks}
        </a>
      ),
      cta: (chunks: ReactNode[]) => (
        <strong className="important">{chunks}</strong>
      )
    }}
  />
Bill Keese
  • 1,792
  • 14
  • 29