在导出函数的命名空间中使用自定义类型

Use Custom types in a namespace that exports a function

我喜欢为 https://github.com/LionC/express-basic-auth

写一个 index.d.ts 文件

但我不知何故陷入了如何在选项对象中声明回调类型的问题。

declare module "express-basic-auth" { 


  import {Handler, Request} from "express";

  function  ExpressBasicAuthorizer(username: string, password: string): boolean;
  function ExpressBasicAuthResponseHandler(req: Request): string|object;

  interface ExpressBasicAuthUsers {
    [username: string]: string;
  }

  interface ExpressBasicAuthOptions {
    challenge?: boolean;
    users?: ExpressBasicAuthUsers; // does not only allow string:string but other ex. string: number too
    authorizer?: ExpressBasicAuthorizer; // *does not work*
    authorizeAsync?: boolean;
    unauthorizedResponse?:  ExpressBasicAuthResponseHandler|string|object; // *does not work*
    realm?: ExpressBasicAuthResponseHandler|string; // *does not work*
  }

  function expressBasicAuth(options?:ExpressBasicAuthOptions): Handler;

  export = expressBasicAuth;

}

我得到:错误 TS2304:找不到名称 'ExpressBasicAuthorizer'

我如何声明 ExpressBasicAuthorizer 和 ExpressBasicAuthResponseHandler 以使其工作?

本例中的 ExpressBasicAuthorizerExpressBasicAuthResponseHandler 需要声明为 "type" 而不是 "function"。试试这个:

declare module "express-basic-auth" {
    import { Handler, Request } from "express";

    type ExpressBasicAuthorizer = (username: string, password: string) => boolean;
    type ExpressBasicAuthResponseHandler = (req: Request) => string | object;

    interface ExpressBasicAuthUsers {
        [username: string]: string | number;
    }

    interface ExpressBasicAuthOptions {
        challenge?: boolean;
        users?: ExpressBasicAuthUsers;
        authorizer?: ExpressBasicAuthorizer;
        authorizeAsync?: boolean;
        unauthorizedResponse?: ExpressBasicAuthResponseHandler | string | object; 
        realm?: ExpressBasicAuthResponseHandler | string;
    }

    function expressBasicAuth(options?: ExpressBasicAuthOptions): Handler;

    export = expressBasicAuth;
}