Use Typescript generics for a type safe `setTimeout` and `setInterval`

TLDR; Here’s the code: type Handler = ((...args: any[]) => any) | string; function safeSetTimeout<F extends Handler>( handler: F, timeout?: number, ...args: F extends string ? any[] : Parameters<F extends string ? never : F> ) { return setTimeout(handler, timeout, ...args); } If you understand everything in the following snippet, you don’t have much to gain from this post. But you might want check out the practical snippet at the end of this post....

March 20, 2022 · 5 min · 956 words · Abdellah Hariti