我想定义具有函数重载的接口并实现它。
我可以这样做:
export interface ServerRoutHandler
{
( opts: any, handlers: RequestHandler );
( opts: any, handlers: RequestHandler[] );
( opts: any, ...handlers: RequestHandler[] );
( opts: any, handlers: RequestCtxHandler );
( opts: any, handlers: RequestCtxHandler[] );
( opts: any, ...handlers: RequestCtxHandler[] );
}
然后这个
get:ServerRoutHandler = ( opts: any, ...handlers: any[] ) =>
{
return this.factoryRouts('GET', opts, handlers);
}
post:ServerRoutHandler = ( opts: any, ...handlers: any[] ) =>
{
return this.factoryRouts('POST', opts, handlers);
}
del:ServerRoutHandler = ( opts: any, ...handlers: any[] ) =>
{
return this.factoryRouts('DELETE', opts, handlers);
}
但它似乎更像是一种解决方法,并略微改变了该函数的行为。
还有其他语法吗?像这样:
get<ServerRoutHandler>( opts: any, ...handlers: any[] )
{
return this.factoryRouts('GET', opts, handlers);
}
// It's not works as expected
答案 0 :(得分:-1)
你这样做的方式,如果你在一个类中实现get
,post
和del
,它们实际上就是函数和可调用的。我看到的唯一问题是你的方式,this
在这些函数中没有明确的类型,因此访问它可能是一个问题。但是,如果您将this
的类型指定为第一个参数,则会解决问题。请注意,此初始this
参数不会向您的函数添加新参数,只是告诉TypeScript this
的类型是什么。这是一个例子:
// I don't have your types. So I'm setting these to strings to that the code compiles.
type RequestHandler = string;
type RequestCtxHandler = string;
interface ServerRouteHandler {
(opts: any, handlers: RequestHandler );
(opts: any, handlers: RequestHandler[] );
(opts: any, ...handlers: RequestHandler[] );
(opts: any, handlers: RequestCtxHandler );
(opts: any, handlers: RequestCtxHandler[] );
(opts: any, ...handlers: RequestCtxHandler[] );
}
// Example class that has methods that fit ServerRouteHandler
class Something {
constructor(public x: number) { }
get: ServerRouteHandler = function get(this: Something, opts: any, ...handlers: any[]) {
console.log("get", this.x, opts, handlers);
}
}
const something = new Something(999);
something.get({}, ["1"]);
如果你运行它,你会在控制台上得到get 999 Object Array[1]
。
我不知道语法会更直接。