通过HOC提供数据,但是在类型“ {}”中缺少调用组件属性“”但在类型“”中必需时出现错误

时间:2019-11-03 12:58:20

标签: javascript reactjs react-hooks higher-order-components

我有以下HOC组件为我的组件提供Firebase:

arcpy.AddMessage("Projection of {0} is {1}, so re-defining projection now: ".format(str(fc), desc.spatialReference.name)

我的组件看起来像这样:

import React from 'react'

const FirebaseContext = React.createContext({})

export const withFirebase = <Props extends object>(
  Component: React.ComponentType<Props>
): React.ComponentType<Props> =>
  class WithFirebase extends React.Component<Props> {
    render(): React.ReactNode {
      return (
        <FirebaseContext.Consumer>
          {(firebase): React.ReactNode => (
            <Component {...this.props} firebase={firebase} />
          )}
        </FirebaseContext.Consumer>
      )
    }
  }

export default FirebaseContext

但是,每当我在页面中调用组件时,都会出现以下错误: import React from 'react' import Firebase, { withFirebase } from '../Firebase' interface FirebaseInterface { firebase: Firebase } const SignInGoogle: React.FC<FirebaseInterface> = ({ firebase }) => { //component content } export default withFirebase(SignInGoogle) Property 'firebase' is missing in type '{}' but required in type 'FirebaseInterface'(我的组件)

我的HOC组件正在提供Firebase,那么如何摆脱此错误?我究竟做错了什么?

1 个答案:

答案 0 :(得分:1)

问题是您实际上减少了withFirebase HOC中所需的属性,但是您的返回类型不能反映出这一点。试试:

import React from 'react'

const FirebaseContext = React.createContext({})

export const withFirebase = <Props extends { firebase: Firebase }>(
  Component: React.ComponentType<Props>
): React.ComponentType<Omit<Props,'firebase'>> =>
  class WithFirebase extends React.Component<Props> {
    render(): React.ReactNode {
      return (
        <FirebaseContext.Consumer>
          {(firebase): React.ReactNode => (
            <Component {...this.props} firebase={firebase} />
          )}
        </FirebaseContext.Consumer>
      )
    }
  }

export default FirebaseContext

Omit助手需要ts 3.5,但也可以在react类型中使用(我认为)。给该点一个需要firebase返回一个不需要的组件

的组件