javascript - React HoC injicera props med typescript


Jag har en React HoC som lägger till två parametrar (funktion för att översätta och aktuell lokal) i komponentens props. Det fungerar bra. Men jag börjar skriva om projektet med TypeScript, och jag har ingen aning om hur man gör det.

Min poäng är mycket lik hur man hanterar props som injiceras av HoC i React med TypeScript. Men jag har en HoC till i min HoC.

import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';

export function withTranslate(Component) {
  function WithTranslate(props) {
    const { intl, ...compProps } = props;
    const translate = key => {
      return intl.formatMessage({
        id: key
      });
    };

    return <Component {...compProps} t={translate} locale={intl.locale} />;
  }

  WithTranslate.displayName = `withTranslate(${Component.displayName ||
    Component.name}`;
  WithTranslate.propTypes = {
    intl: PropTypes.shape({
      locale: PropTypes.string.isRequired,
      formatMessage: PropTypes.func.isRequired
    }).isRequired
  };
  return injectIntl(WithTranslate);
}

injectIntl från "react-intl" har typer

interface InjectedIntlProps {
    intl: InjectedIntl;
}

interface InjectIntlConfig {
    intlPropName?: string;
    withRef?: boolean;
}

function injectIntl<P>(component: React.ComponentType<P & InjectedIntlProps>, options?: InjectIntlConfig):
React.ComponentClass<Pick<P, Exclude<keyof P, keyof InjectedIntlProps>>> & { WrappedComponent: React.ComponentType<P & InjectedIntlProps> };

Jag försöker göra detta med

interface WithTranslateProps {
  t: (key:string) => string;
  locale: string;
}

export function withTranslate<T extends object>(Component:ComponentType<T & WithTranslateProps>):
  ComponentType<T & WithTranslateProps> {
  function WithTranslate<P>(props:P & InjectedIntlProps) {
    const { intl, ...compProps } = props;
    const translate = (key:string) => {
      return intl.formatMessage({
        id: key
      });
    };

    return <Component {...compProps} t={translate} locale={intl.locale} />;
  }

  WithTranslate.displayName = `withTranslate(${Component.displayName ||
  Component.name}`;

  return injectIntl(WithTranslate);
}

Det fungerar inte.

TS2322: Typen '{ t: (key: string) => string; locale: string; }' kan inte tilldelas typen 'T'.

TS2322: Typen 'ComponentClass, any> & { WrappedComponent: ComponentType; }' kan inte tilldelas typen 'ComponentType'. Typen 'ComponentClass, any> & { WrappedComponent: ComponentType; }' kan inte tilldelas typen 'ComponentClass'. Typen 'Component, any, any>' kan inte tilldelas typen 'Component'. Typerna för egenskapen 'props' är inkompatibla. Typen 'Readonly<{ children?: ReactNode; }> & Readonly' kan inte tilldelas typen 'Readonly<{ children?: ReactNode; }> & Readonly'. Typen 'Readonly<{ children?: ReactNode; }> & Readonly' kan inte tilldelas typen 'Readonly'.

Kan någon hjälpa mig?