Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 18095

How to select a type for a method based on the generic type provided in the class in TypeScript?

$
0
0

I have the following class:

class Processor<TReq, TRes> {    constructor(        private handler: (input: TReq) => TRes    ) {}    public handleRequest(input: TReq): TRes {       ...       const res = this.handler(input);       ...    }}

In this design, I can do this:

const myProcessor = new Processor<string, string>(    (input: string) => `Hello ${input}`);myProcessor.handleRequest('Hello');

My issue is that I want to be able to pass never to TReq, and when that happens, I would like handleRequest to be of type () => TRes, and handler as well:

const myProcessor = new Processor<never, string>(    () => 'Hi');myProcessor.handleRequest();

How can I achieve this?


Viewing all articles
Browse latest Browse all 18095

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>