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

时间:2017-03-27 11:45:51

标签: typescript typescript-types

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

编写index.d.ts文件

但我在某种程度上坚持如何在options对象中声明回调类型。

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以使其有效?

1 个答案:

答案 0 :(得分:0)

在这种情况下,ExpressBasicAuthorizerExpressBasicAuthResponseHandler需要声明为“类型”而不是“函数”。试试这个:

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;
}