我创建了一个简单的 HOC,它translate
在组件中注入了一个方法。
export interface IMessageProps {
translate: (key: string) => string;
}
export const message = <P extends object>(
Component: React.ComponentType<P & IMessageProps>
): React.SFC<P & IMessageProps> => (props: P) => {
const translate = (key: string): string => messages[key];
return <Component {...props} translate={translate}/>;
};
用法:
class MyComponent extends React.Component<IMessageProps, {}> {
render() {
return (
<>{this.props.translate('hello.world')}</>
);
}
}
export default message(MyComponent);
当我想调用我的组件时问题就出现了,<MyComponent/>
因为 tsc 抱怨该属性translate
没有传递给MyComponent
并期望像<MyComponent translate={...}/>
.
Type '{}' is not assignable to type 'IntrinsicAttributes & IMessageProps & { children?: ReactNode; }'.
Type '{}' is not assignable to type 'IMessageProps'.
Property 'translate' is missing in type '{}'.
所以我的问题是:如何绕过这个假错误?我不想成为translate
可选的,IMessageProps
因为 tslint 会抱怨Cannot invoke an object which is possibly 'undefined'
.