Closed
Description
Bug Report
When modifying a variable with a type Union of objects, the inferred type should be the Union of the possible results.
🔎 Search Terms
- Union
- Narrow union
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Union and narrow
⏯ Playground Link
Playground link with relevant code
💻 Code
type Source = {
type: 'ws'
reader: {state: 'connecting'}
} | {
type: 'file'
reader: {state: number}
}
let source: Source = {type: 'file', reader: {state: 12}}
/*
* Error: getSourceWithState return type is
* {
* type: "ws" | "file";
* state: "connecting" | number;
* }
* instead of
* {
* type: "file";
* state: number;
* } |
* {
* type: "ws";
* state: "connecting";
* }
*/
const getSourceWithState = () => {
return {
type: source.type,
state: source.reader.state
}
}
const sourceWithState = getSourceWithState()
if (sourceWithState.type === 'file') {
// Error
sourceWithState.state += 1
}
🙁 Actual behavior
The return type of getSourceWithState is
{
type: "ws" | "file";
state: "connecting" | number;
}
Then trying to narrow the type is impossible.
🙂 Expected behavior
The return type of getSourceWithState should be
{
type: "file";
state: number;
} |
{
type: "ws";
state: "connecting";
}
This would make it possible to narrow the type and is also the truth.
Metadata
Metadata
Assignees
Labels
No labels