I like to write a index.d.ts file for https://github.com/LionC/express-basic-auth
But I am somehow stuck in how to declare the types for callbacks within the options object.
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;
}
I get: error TS2304: Cannot find name 'ExpressBasicAuthorizer'
How can I declare ExpressBasicAuthorizer and ExpressBasicAuthResponseHandler so that it works?
The ExpressBasicAuthorizer
and ExpressBasicAuthResponseHandler
in this case needs to be declared as a "type" and not a "function". Try this:
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;
}