具有功能参数的对象的索引签名

时间:2018-10-29 09:35:31

标签: typescript

关于棘手的语法问题,我需要一些建议。我对所有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创建索引签名或键入强制转换来避免TS错误?

1 个答案:

答案 0 :(得分:1)

您可以这样投射它:

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

还有其他答案。