T
T
tonyshow2019-07-23 05:33:43
typescript
tonyshow, 2019-07-23 05:33:43

How in typescript to dynamically call and define an instance of classes and their method through new some_client[class_name]()?

There is a .ts client generated by nswag; it has a set of classes and methods that need to be called dynamically by substituting the names of classes and their methods into the call functions.
Code example:
5d3671a005c68896500250.png

import * as client from './nswag/clients';
import { errorsStore } from '../stores';

interface IClass {
  [key: string]: () => any
}

function requestsHandling<T, X, U>(cb: (_: T) => X | void, cls: string, method: string, params?: U) {
  const fn = new client[cls]<IClass>();
  const request = async () => await fn[method](params);
  return request()
    .then(async (result) => {
      const res = await result;
      console.log(res);
      cb(res);
    })
    .catch((err) => {
      errorsStore.addError(err);
    });
};
export default requestsHandling;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question