Can the declaration of the resolve
variable in the TypeScript code below be simplified while maintaining type safety? I am new to TypeScript, so please bear with me.
The objective is to store the promise resolver callback that is passed to the executor function so that it can be invoked later outside of it. The initial idea I came up with is
let resolve: ((v: number) => void) | null = null
. Give it a try in the TS Playground:
function timeout(ms: number): Promise<number> {
// store the promise's resolver for later invocation
let resolve: ((v: number) => void) | null = null; // <===
const p = new Promise<number>(r => resolve = r);
const start = performance.now();
setTimeout(() => resolve!(performance.now() - start), ms);
return p;
}
If I do not use a union type with null
, TypeScript will rightfully raise an error saying that resolve
might be uninitialized when called later on:
setTimeout(() => resolve(...), ms)
. Is there a more concise way to achieve this without introducing any
or TypeScript errors?
To clarify, the example above may seem overly complex, and could be simplified as follows:
function timeout(ms: number): Promise<number> {
const start = performance.now();
return new Promise<number>(r =>
setTimeout(() => r(performance.now() - start)));
}
However, the main focus here is on the TypeScript syntax. The actual code does require storing the promise's resolve
and reject
callbacks to implement the Deferred
pattern.