gpt4 book ai didi

typescript - 具有函数参数的对象的索引签名

转载 作者:搜寻专家 更新时间:2023-10-30 21:47:05 27 4
gpt4 key购买 nike

我需要一些关于棘手语法问题的建议。我有一个更长的所有 HTTP 方法列表,想调用适当的用户函数。

简化代码:

const httpMethods = {
'connect': this.connect(req, res),
'copy': this.copy(req, res),
'delete': this.delete(req, res),
'get': this.get(req, res),
...
}

let callFunction = httpMethods['get']
callFunction(req, res)

如何为对象 httpMethods 创建索引签名或类型转换 callFunction 以避免 TS 错误?

最佳答案

你可以这样转换它:

let key = "get";
let callFunction = (<any>httpMethods)[key];
callFunction(req, res);

或者像这样:

interface ISomeObject {
connect: any;
copy: any;
delete: any;
get: any;
[key: string]: any;
}

const httpMethods: ISomeObject = {
'connect': this.connect(req, res),
'copy': this.copy(req, res),
'delete': this.delete(req, res),
'get': this.get(req, res),
...
}

let key: string = "get";
let callFunction = httpMethods[key];
callFunction(req, res);

我从这个答案中改编了一个例子:https://stackoverflow.com/a/35209016/3914072

还有其他答案。

关于typescript - 具有函数参数的对象的索引签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53042530/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com