Reactjs 使用typescript进行有点复杂的React函数组件声明 constwithauth=()=>( 组件:React.ComponentType ) => { } (withAuth()(PrivateRoute))//这就是HOC调用

Reactjs 使用typescript进行有点复杂的React函数组件声明 constwithauth=()=>( 组件:React.ComponentType ) => { } (withAuth()(PrivateRoute))//这就是HOC调用,reactjs,typescript,Reactjs,Typescript,有人能用外行术语解释这个函数声明吗?我知道这是一个特别的问题,但什么是原创的?语法不清楚 我不会含糊地说,如果删除了原始rops const withAuth = () => <OriginalProps extends {}>( Component: React.ComponentType<OriginalProps & IAuthContextInterface> ) => { } (withAuth()(PrivateRoute)) //

有人能用外行术语解释这个函数声明吗?我知道这是一个特别的问题,但什么是原创的?语法不清楚

我不会含糊地说,如果删除了原始rops

const withAuth = () => <OriginalProps extends {}>(
  Component: React.ComponentType<OriginalProps & IAuthContextInterface>
) => { }

(withAuth()(PrivateRoute)) // this is how the HOC called
constwithauth=()=>(
组件:React.ComponentType
) => { }
您看到的是一个,而
OriginalProps
是一个类型变量或类型参数

重要在继续之前,请先阅读上面的链接以了解泛型的概念。对泛型的基本理解是以下解释的前提

由于arrow函数的简洁性,语法有点模糊,让我们将其转换回老式的
函数

const withAuth = () => (
      Component: React.ComponentType<OriginalProps & IAuthContextInterface>
    ) => { }
现在应该清楚了,
withAuth
是一个返回匿名函数的函数。此匿名函数也是一个通用函数,它接受一个类型参数,该参数可从
组件的类型
参数推断

整个事情是这样的:

  • 我们有这个
    T
    type参数,其类型值我们还不知道,但它与
    组件的类型值相关
  • 我们要求
    Component
    参数的类型为
    React.ComponentType
    ,但是
    的某些内容还不清楚
  • 当我们用auth()调用
    (PrivateRoute)
    时,我们可以知道
    PrivateRoute
    中的
    内容是什么
  • 同样,假设我们已经知道了
    IAuthContextInterface
    ,我们可以知道
    T
    的确切类型值,就像解一个方程一样:

这是一种从包装组件推断道具类型的方法,无需在
withAuth
call上显式指定道具类型。看见这不是具体的反应。
React.ComponentType
是否适合
Component
取决于您的情况。谢谢@hackape。有道理!
function withAuth() {
  return function<OriginalProps extends {}>(Component: React.ComponentType<OriginalProps & IAuthContextInterface>) { ... }
}
function withAuth() {
  return function<T>(Component: React.ComponentType<T & IAuthContextInterface>) { ... }
}
Something = T + IAuthContextInterface
=> T = Something - IAuthContextInterface

// here =, +, - signs are just analogue, not real typescript operators