我在为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; }'.`
答案 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>> {};
};