TypeScript Version: 3.1.0-dev.201xxxxx
Search Terms:
- type literal promises
- type inferred promises
Code
interface ResponseA {
type: 'A',
payload: any,
}
interface ResponseB {
type: 'B',
payload: any,
}
type ResponseKind = ResponseA | ResponseB;
// Does not work in strict mode
async function returnResponseAsync(): Promise<ResponseKind> {
const type = 'A';
const payload = {};
return await {
type, // type is 'string' type
payload
}
}
// Works in strict mode
function returnResponse(): ResponseKind {
const type = 'A';
const payload = {};
return {
type, // type is 'A' type
payload
}
}
This is a minimum reproducible code but I found this working with a complex scenario of observables and promises. However, the bug is still reproducible, because the type is being lose.
Expected behavior:
Inside the promise type type should be inferred as well.
Actual behavior:
Throws because string is not assignable to neither A or B.
Playground Link:
Link using async/await
Link with Promise.resolve
Link with Observable
Related Issues:
Workaround:
Just type the variable with a literal type.
async function returnResponseAsync(): Promise<ResponseKind> {
const type: 'A' = 'A';
const payload = {};
return await {
type, // type is 'A' type
payload
}
}
TypeScript Version: 3.1.0-dev.201xxxxx
Search Terms:
Code
This is a minimum reproducible code but I found this working with a complex scenario of observables and promises. However, the bug is still reproducible, because the type is being lose.
Expected behavior:
Inside the promise
typetype should be inferred as well.Actual behavior:
Throws because
stringis not assignable to neitherAorB.Playground Link:
Link using async/await
Link with Promise.resolve
Link with Observable
Related Issues:
Workaround:
Just type the variable with a literal type.