Reputation: 16264
The following won't compile:
function P() {
return new Promise((resolve, reject) => {
const stringValue:string = "...explicit string...";
resolve(stringValue);
});
}
async function f() {
let s:string = "";
await P().then((res) => { s = res; });
}
The error is at the statement s = res
:
[ts] Type '{}' is not assignable to type 'string'.
Why is this happening?
Upvotes: 0
Views: 50
Reputation: 39946
You have to explicitly specify return type.
function P(): Promise<string> {
return new Promise((resolve, reject) => {
const stringValue:string = "...explicit string...";
resolve(stringValue);
});
}
async function f() {
let s:string = "";
await P().then((res) => { s = res; });
}
TypeScript assumes return type of P is Promise<{}>
when you do not specify return type. You can check it at https://www.typescriptlang.org/play/index.html , type your code on left side and put mouse on P().then(
, you will see that typescript assumes return type as Promise<{}>
.
Upvotes: 1