create a typed async settimeout function in typescript

To create a typed async setTimeout function in TypeScript, you can use the Promise class and the setTimeout function to create a delay.

index.ts
function delay(ms: number) {
  return new Promise<void>((resolve) => setTimeout(resolve, ms));
}

async function typedSetTimeout(delayMs: number, callback: () => void): Promise<void> {
  await delay(delayMs);
  callback();
}
225 chars
9 lines

Here, the delay function returns a Promise that resolves after the specified delay time. The typedSetTimeout function then calls the delay function before executing the provided callback.

This typed setTimout function is now valid and can be used as such:

index.ts
typedSetTimeout(1000, () => console.log("Hello, world!"));
59 chars
2 lines

gistlibby LogSnag