Closed
Description
Suggestion
This should work:
interface A {
foo: string
}
interface B {
bar: string
}
type C = A | B
const a = {foo: 'bar'} as C
if (a.foo) {
console.log(a.foo)
} else {
console.log(a.bar)
}
I think the compiler should be able to infer the types here. Its a very common pattern to return e.g. (SuccessResponse | ErrorResponse) and without inference it becomes very inconvenient to handle. I apologize if this has been discussed before, it seems like it should have been but I couldn't find anything with a quick search.
π Search Terms
Infer union types
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Metadata
Metadata
Assignees
Labels
No labels