React-intl, use api with Typescript

两盒软妹~` 提交于 2019-12-05 02:57:04

While working with the same problem, I found that neither including InjectedIntlProps as a member, as mentioned in the question, nor extending from it, as mentioned in another answer, satisfies the type checker. When extending from InjectedIntlProps, the call to injectIntl checked, but using the resulting component in JSX expected me to provide an intl property. The following strategy resolved this though:

    interface NameFormProps {
        // Include all custom properties here.
    }

    class NameForm extends React.Component<NameFormProps & InjectedIntlProps, {}> {
        // Class body.
    }

    export default injectIntl(NameForm);

The problem was due to the version of the typescript definition. When using @types/react-intl": "^2.2.0", it works like a charm.

(edit) Few changes needed to make it work :

//index.tsx
<IntlProvider locale={`fr-FR`} messages={messages_fr}>
  <NameForm/>
</IntlProvider>,

//nameForm.tsx
interface NameFormProps extends InjectedIntlProps {
  placeholder: string,
}

class NameForm extends React.Component<NameFormProps, {}> {

  render() {
    let namePlaceholder = this.props.intl.formatMessage({
       id: this.props.placeholder,
       defaultMessage: "name"
      });

    return (
      <form>
        <input placeholder={namePlaceholder} type="text"/>
      </form>
    );
}

export default injectIntl(NameForm);

Neither of the existing solutions worked for me. Instead it was due to injectIntl inferring the properties to include InjectedIntlProps.

To fix it, I had to explicitly tell injectIntl what props the wrapped component should have:

interface NameFormProps {
}

class NameForm extends React.Component<NameFormProps & InjectedIntlProps> {
}

export default injectIntl<NameFormProps>(NameForm);

If there are no props, it needs to be changed slightly:

class NameForm extends React.Component<InjectedIntlProps> {
}

export default injectIntl<{}>(NameForm);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!