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

后端 未结 1 1485
轻奢々
轻奢々 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 = 

    ( Component: React.ComponentType

    ): React.SFC>> => (props: Pick>) => { const translate = (key: string): string => messages[key]; return ; };

    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 = 

    ( Component: React.ComponentType

    ): React.SFC>> => (props: Pick>) => { const translate = (key: string): string => messages[key]; return ; }; class MyComponent extends React.Component { render() { return ( <>{this.props.translate('hello.world')} ); } } const MyComponentWrapped = message(MyComponent); let d = // works

    3.5 and above

    You can use Omit instead of Pick>

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