javascriptreactjstypescriptreact-intl

FormattedMessage values chunks using typescript


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?


Solution

  • 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>
          )
        }}
      />