2

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?

Andy Brunner
  • 133
  • 3
  • 12
  • what TS errors are you getting exactly? Can you add the error trace here? – AkshayM Oct 29 '18 at 09:50
  • The error in German is:

    TS 7017, "Das Element weist implizit einen Typ \"any\" auf, weil der Typ \"{ 'connect': void; 'copy': void; 'delete': void; 'get': void; 'head': void; 'link': void; 'lock': void; 'options': void; 'patch': void; 'post': void; 'pri': void; 'propfind': void; 'purge': void; 'put': void; 'trace': void; 'unlink': void; 'unlock': void; 'view': void; }\" keine Indexsignatur umfasst."
    Code is as follows:
    let methodFunction = httpMethods[requestData.httpMethod] methodFunction(requestData, response)
    – Andy Brunner Oct 29 '18 at 10:26

1 Answers1

1

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.

Rajab Shakirov
  • 7,265
  • 7
  • 28
  • 42