It seems that Promises in Typescript can be type-unsafe. This simple example demonstrates that the resolve
function accepts undefined
, while Promise.then
infers the argument to be non-undefined
:
function f() {
return new Promise<number>((resolve) => {
resolve(undefined)
})
}
f().then((value) => {
console.log(value+1)
})
(tested in my current project and on ).
Currently, Typescript interprets the type of value
as number
instead of
number | PromiseLike<number> | undefined
.
This issue may be specific to Typescript at the moment, but...
What is a suitable workaround? I want the compiler to alert me if value
could be undefined!
A straightforward solution could be:
f().then((value:number | undefined) => {
console.log(value+1) // now I get: Object is possibly 'undefined'
})
However, this means having to consciously address the problem every time it's called.
EDIT (current status): Following the solution provided by @JerMah, I encapsulated the creation of the Promise
within a generic function:
function makePromise<T>(executor: (resolve: (value: T) => void,
reject: (reason?: any) => void) => void)
{
return new Promise<T>(executor);
}