我有一个react HoC,它将两个参数(转换功能和当前语言环境)添加到组件prop中。很好但是我开始用TypeScript重写项目,我也不知道该怎么做。
我的观点与how-to-handle-props-injected-by-hoc-in-react-with-typescript非常相似。但是我的HoC中又有一个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);
}
“ react-intl”中的injectIntl具有键入内容
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> };
我尝试用
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);
}
不起作用。
TS2322:键入'{t:(key:string)=> string;语言环境:字符串; }”不能分配给类型“ T”。
TS2322:类型为'ComponentClass,任意>&{WrappedComponent:ComponentType; }”不可分配给“ ComponentType”类型。 类型'ComponentClass,任何>&{WrappedComponent:ComponentType; }”不可分配给“ ComponentClass”类型。 类型'Component,any,any>'不能分配给'Component'类型。 属性“ props”的类型不兼容。 输入'Readonly <{children ?: ReactNode; }>&Readonly>'不可分配为类型'Readonly <{children ?: ReactNode; }>和“只读”。 输入'Readonly <{children ?: ReactNode; }>和“只读”>不能分配为“只读”类型。
有人可以帮助我吗?