Typescript - 高阶函数的类型定义

Typescript - Type definition for a higher order function

我正在使用 Okta React 库 - https://github.com/okta/okta-oidc-js/tree/master/packages/okta-react 但是它没有类型定义。

我创建了一个 .d.ts 定义文件,其中包含 declare module "@okta/okta-react" 但是这个库有一个高阶组件,例如:import { withAuth } from '@okta/okta-react'; (https://github.com/okta/okta-oidc-js/tree/master/packages/okta-react#withauth)

如何在我的定义文件中写入它?

这有效吗?

declare module "@okta/okta-react" {
    function withAuth(any): any
}

我已经为 withAuth 提供的方法编写了一个接口,例如:

interface OktaWithAuth {
    /**
     * Returns true or false, depending on whether the user has an active access or id token.
     */
    isAuthenticated(): Promise<boolean>;
....
}

谢谢。

您需要使 withAuth 成为一个通用函数,该函数接受一个组件类型和 returns 该组件类型,但修改 props 以删除 auth:


declare module "@okta/okta-react" {
  import React from 'react'
  function withAuth<P extends { auth: OktaWithAuth }>(comp: React.ComponentType<P>): React.ComponentType<Omit<P, 'auth'>>
  interface OktaWithAuth {
      /**
       * Returns true or false, depending on whether the user has an active access or id token.
       */
      isAuthenticated(): Promise<boolean>;

  }
}

游乐场示例:Playground Link

Omit<P, 'auth'> 使用预定义的 Omit 帮助程序类型从 P 中删除 auth 属性。这意味着返回的组件将具有与输入组件相同的道具,但没有 withAuth.

提供的 auth 属性