Andy Brunner
Andy Brunner

Reputation: 173

Index signature for objects with function parameters

I need some advice on a tricky syntax problem. I have a longer list of all HTTP methods and would like to call the appropriate user function.

Simplified code:

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)

How can I create an index signature for the object httpMethods or type cast the callFunction to avoid TS errors?

Upvotes: 2

Views: 397

Answers (1)

Rajab Shakirov
Rajab Shakirov

Reputation: 8005

You could cast it like this:

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

or like this:

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);

I adapted an example from this answer: https://stackoverflow.com/a/35209016/3914072

There are additional answers too.

Upvotes: 1

Related Questions