简体   繁体   English

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

[英]Writing declaration d.ts file for existing HOC

I'm having problem with writing a d.ts file for a HOC component: with-apollo-client.js wraps an component to inject a prop in. It is something like this: 我在为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}>
    }
  }
}

To use it, we just do: 要使用它,我们只需要:

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

And in with-apollo-client.d.ts 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> {};
};

And TS is complaining: TS抱怨:

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

You need to remove the interface WithApolloClient from your returned React.Component. 您需要从返回的React.Component中删除WithApolloClient接口。 Otherwise it will expect an apolloClient as prop. 否则,它将期望apolloClient作为道具。 Something like this should work: 这样的事情应该起作用:

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>> {};
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM