2017-03-27 61 views
0

命名空間,我喜歡寫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使其作品?

回答

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