首页 > 解决方案 > 在与 Typescript 的反应中正确注释 HOC

问题描述

我在正确注释以下 HOC 时遇到了困难。我不知道要为函数的返回类型添加什么,也不知道如何注释道具。我总是遇到错误。


const withAuthentication = <Props extends object>(
  Component: React.ComponentType<Props>
) => {
  const WithAuthentication = (props: Any) => {
    const { firebase } = props

    return (
      <AuthUserContext.Provider value={authenticated}>
        <Component {...(props as Props)} />
      </AuthUserContext.Provider>
    )
  }

  return withFirebase(WithAuthentication)
}

有谁知道如何解决这个问题?非常感谢您的帮助!

标签: reactjstypescripthigher-order-components

解决方案


在 typescript 中指定匿名函数表达式的返回类型的正确方法如下所示。类型说明在参数声明之后

const withAuthentication = (
    Component: React.ComponentType<Props>
) : React.Component<Props> => {
    const WithAuthentication = (props: any) => {
        const { firebase } = props;

        return (
            <AuthUserContext.Provider value={authenticated}>
                <Component {...(props as Props)} />
            </AuthUserContext.Provider>
        );
    };

    return withFirebase(WithAuthentication);
};


推荐阅读