【问题标题】:Use Custom types in a namespace that exports a function在导出函数的命名空间中使用自定义类型
【发布时间】:2017-08-20 02:36:30
【问题描述】:

我喜欢为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 以使其正常工作?

【问题讨论】:

    标签: typescript typescript-types


    【解决方案1】:

    在这种情况下,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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 2019-09-21
      • 2015-03-17
      • 2014-06-10
      • 2012-01-20
      • 2014-08-12
      相关资源
      最近更新 更多