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

Posted

技术标签:

【中文标题】在导出函数的命名空间中使用自定义类型【英文标题】: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 以使其正常工作?

【问题讨论】:

【参考方案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;

【讨论】:

以上是关于在导出函数的命名空间中使用自定义类型的主要内容,如果未能解决你的问题,请参考以下文章

为 Qt 注册自定义类型时,何时、何地以及为何使用命名空间

如何导入***元素是非导出命名空间的 Typescript 类型定义文件?

无法重命名自定义帖子类型的 slug

如何在我的自定义类型中包含非命名模块 TS 定义

WebAPI 2.2 中没有命名空间的 OData v4 自定义函数

如何自定义 WCF XML 序列化