Related post, I want to statically check if a Promise
is guaranteed to resolve
or reject
:
function foo(x: number) {
return new Promise((resolve, reject) => {
if (x > 30) { resolve(x+7); }
if (x < 20) { reject("ouch !!!"); }
});
}
async function main() {
try { const y = await(foo(60)); console.log(y); }
catch (e) { console.log(e); }
}
main();
Can the approach for enums coverage (from this post) be extended to number
coverage?
EDIT:
I guess for the very least I would like to specify the
return type of the promise so an undefined
is not a
valid value. Something similar to:
$ cat example.ts
function bar(x: number): number { if (x > 30) { return x-2; }}
$ npx tsc --strict --target es2020 example.ts | grep error
example.ts(1,26): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
// ~! Function lacks ending return statement and return type does not include 'undefined'.(2366)
async function foo(x: number): Promise<number> {
if (x > 30) { return (x + 7); }
if (x < 20) { throw new Error("ouch !!!"); }
}
Promises are especially used in cases where you have no idea when you return something