为现有HOC编写声明d.ts文件

时间:2018-11-07 23:16:39

标签: reactjs typescript

我在为HOC组件编写d.ts文件时遇到问题: with-apollo-client.js包装了一个组件以注入道具。就像这样:

export default App => {
  return class Apollo extends React.Component{
    render(){
       // code to get apolloClient variable omitted

       <Apollo client={apolloClient}>
    }
  }
}

要使用它,我们要做:

import withApolloClient from './with-apollo-client'
...
export default withApolloClient(App)

with-apollo-client.d.ts

import { ApolloClient } from 'apollo-boost';

export interface WithApolloClient {
    apolloClient: ApolloClient<any>;
}

export default <P extends WithApolloClient>(App: React.ComponentType<P>) => {
    return class Apollo extends React.Component<P> {};
};

TS抱怨:

`Type '{ id: string; }' is not assignable to type 'Readonly<Props>'.
  Property 'apolloClient' is missing in type '{ id: string; }'.`

1 个答案:

答案 0 :(得分:1)

您需要从返回的React.Component中删除WithApolloClient接口。否则,它将期望apolloClient作为道具。这样的事情应该起作用:

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
type Subtract<T, K> = Omit<T, keyof K>;

export default <P extends WithApolloClient>(App: React.ComponentType<P>) => {
  return class Apollo extends React.Component<Subtract<P, WithApolloClient>> {};
};