How to handle props injected by HOC in React with Typescript?

后端 未结 1 1474
轻奢々
轻奢々 2020-12-17 01:09

I created a simple HOC that inject a method translate in a component.

export interface IMessageProps {
  translate: (key: string) => string;         


        
相关标签:
1条回答
  • 2020-12-17 01:48

    Edit

    Typescript 3.2 breaks the code below. Until 3.2 spread operations with generic type parameters were not allowed except for jsx tags and were not very tightly checked there. This issue changes this. Spread operations are not more tightly checked and the this breaks out code. The simplest adjustment we can make is to use a type assertion on props :

    export const message = <P extends IMessageProps>(
        Component: React.ComponentType<P>
    ): React.SFC<Pick<P, Exclude<keyof P, keyof IMessageProps>>> => (props: Pick<P, Exclude<keyof P, keyof IMessageProps>>) => {
    
        const translate = (key: string): string => messages[key];
    
        return <Component {...props as P} translate={translate} />;
    };
    

    Before 3.2

    You can just exclude the properties of IMessageProps from the returned SCF using Pick to pick properties from P and Exclude to exclude the keys of IMessageProps

    export interface IMessageProps {
        translate: (key: string) => string;
    }
    
    export const message = <P extends IMessageProps>(
        Component: React.ComponentType<P>
    ): React.SFC<Pick<P, Exclude<keyof P, keyof IMessageProps>>> => (props: Pick<P, Exclude<keyof P, keyof IMessageProps>>) => {
    
        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')}</>
            );
        }
    }
    
    const MyComponentWrapped = message(MyComponent);
    
    let d = <MyComponentWrapped /> // works
    

    3.5 and above

    You can use Omit<P, keyof IMessageProps> instead of Pick<P, Exclude<keyof P, keyof IMessageProps>>

    0 讨论(0)
提交回复
热议问题