Promises seem to be kind of type-unsafe in Typescript. This simple example shows that resolve accepts undefined, whereas Promise.then seems to infer the argument to be non-undefined:
function f() {
return new Promise<number>((resolve) => {
resolve(undefined)
})
}
f().then((value) => {
console.log(value+1)
})
(tried in my current project an on http://www.staging-typescript.org/play).
Apparently, Typescript infers the type of value to be number, instead of number | PromiseLike<number> | undefined.
This may be a current Typescript issue, but...
What is an appropriate workaround? I'd like the compiler to warn me that value may be undefinded!
A very simple solution could be to write
f().then((value:number | undefined) => {
console.log(value+1) // now I have: Object is possibly 'undefined'
})
but that requires me to actively think about the problem at every call site.
EDIT (current status): Following the solution given by @JerMah, I wrapped the Promise creation in a generic function:
function makePromise<T>(executor: (resolve: (value: T) => void,
reject: (reason?: any) => void) => void)
{
return new Promise<T>(executor);
}