I have a react HoC which is add two params (function to translate and current locale) into component props. It's works good. But i start rewrite project with TypeScript, and i have no idea how to do that.
My point is very similar as how-to-handle-props-injected-by-hoc-in-react-with-typescript. But i have one more HoC into my 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 from "react-intl" have typings
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> };
I try to do this with
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);
}
It's not working.
TS2322: Type '{ t: (key: string) => string; locale: string; }' is not assignable to type 'T'.
TS2322: Type 'ComponentClass, any> & { WrappedComponent: ComponentType; }' is not assignable to type 'ComponentType'. Type 'ComponentClass, any> & { WrappedComponent: ComponentType; }' is not assignable to type 'ComponentClass'. Type 'Component, any, any>' is not assignable to type 'Component'. Types of property 'props' are incompatible. Type 'Readonly<{ children?: ReactNode; }> & Readonly>' is not assignable to type 'Readonly<{ children?: ReactNode; }> & Readonly'. Type 'Readonly<{ children?: ReactNode; }> & Readonly>' is not assignable to type 'Readonly'.
Can anyone help me?