现在我有一个非常通用的函数,当我的客户端与我的服务器交谈时,它会命中。所以为了保持它非常灵活,我这样做:
public call(method: string, ...parameters: any[]) {}
不过,在我的服务器上,我将所有方法放在一起,如下所示:
MethodManager.methods({
findOne: {
function: function(collection: string, query: Object) {
return model(collection).findOne(query).exec();
}
},
find: {
function: function(collection: string, query: Object, sortQuery: Object = {}) {
return model(collection).find(query).sort(sortQuery).exec();
}
}
}
如您所见,每个方法可能有不同的参数。当我在客户端编写代码时,我无法使用 Typescript 的全部潜力,因为它是“任意”类型的。
我怎样才能做到这一点,以便 Visual Studio 代码能够在我编写这行代码时识别出这一点:
this.socketManager.call('findOne',
它会弹出一个帮助列表,如下所示:
(method: 'findOne', collection: string, query: Object)
但是当我输入:
this.socketManager.call('find',
它给了我:
(method: 'find', collection: string, query: Object, sortQuery: Object = {})
而不是无益的:
(method: string, ...parameters: any[])
这可能吗?这将是对发展的巨大帮助。
最佳答案
你可以用 Typescript 中的函数重载做这样的事情:https://www.typescriptlang.org/docs/handbook/functions.html
这是an example :
function call(method: "find", collection: string, query: object): object;
function call(method: "findOne", collection: string, query: object, sortQuery: object): object[];
function call(method: "find" | "findOne", ...parameters: any[]): any {
switch (method) {
case "find": {
const [collection, query] = parameters
return {}
}
case "findOne": {
const [collection, query, sortQuery] = parameters
return [{}]
}
}
}
call("find", "collection", {})
call("findOne", "collection", {}, {})
call("find", "collection", {}, {}) // Error
call("findOne", "collection", {}) // Error
关于基于第一个参数的函数参数动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53455042/