typescriptreact-intl

react-intl - Type '(string | MessageFormatElement)' is not assignable to type 'string'


I am using react-intl for i18n in react with TS. I am getting my translated string using the hook

const intl = useIntl();
intl.messages['my.key']

However, TS throws an error

Type '(string | MessageFormatElement)' is not assignable to type 'string'

How to instruct react-intl to return me string?


Solution

  • Rather than trying to access the internals of the message, you can use the useful formatMessage function to convert the message to a string given the ID:

    const {formatMessage} = useIntl();
    console.log(formatMessage({id: 'my.key'});