React HOC上的打字稿

时间:2019-06-12 11:28:29

标签: javascript reactjs typescript eslint

我有一个像这样的React HOC:

import React from 'react';
import { CookiesConsumer } from './index';

const withCookies = (WrappedComponent: any) => (props: any) => (
  <CookiesConsumer>
    {cookies => (
      <WrappedComponent
        {...props}
        cookiesContext={cookies}
      />
    )}
  </CookiesConsumer>
);

export default withCookies;

我收到2个我要解决的Typescript附带警告。两者都在any类型声明上:

Unexpected any. Specify a different type.eslint(@typescript-eslint/no-explicit-any)

对于props类型,我不知道props对象中可能包含哪些属性或值类型,那么我如何比any更好地定义它?

对于WrappedComponent类型,我尝试使用ReactNodeReactElement之类的类型,但这在JSX element type 'WrappedComponent' does not have any construct or call signatures.

的实际用法上引发了新的错误。

1 个答案:

答案 0 :(得分:7)

import React from 'react';
import { CookiesConsumer } from './index';

interface withCookiesProps {
    someProp: boolean;
  }


const withCookies = <P extends object>(WrappedComponent: React.ComponentType<P>) => (props: P & withCookiesProps) => (
  <CookiesConsumer>
    {cookies => (
      <WrappedComponent
        {...props}
        cookiesContext={cookies}
      />
    )}
  </CookiesConsumer>
);

export default withCookies;

Refernence