Skip to content

Mapping one discriminated union to another discriminated union does not work as expectedΒ #55316

Closed
@wbolduc

Description

@wbolduc

πŸ”Ž Search Terms

discriminated union destructuring

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about discriminated unions (there are none)

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.0-beta#code/JYOwLgpgTgZghgYwgAgJIGcAyB7OATUAc2QG8AoASABtc8I8AuZeK9CAbkuwCMArJnrwgIwyAD7IAriDoxQ9TgF8yoSLEQoc+eqUo1tjZGCiSOXPgL7CwSsmACeABxQBZOPe4QtdPMgC8aFi0ROLI3gpkKuDQ8EiB3kQATLrUtPSJTCxsnBSClkIiodKy8ni2qjEaYWl4yeSpBhlGJma5FsiC1rYOzshuHl41yQEYCSCEyRLhtZxkCNgg6KLocAC2jlQoAQAUq1RM-Z7TAJQH7kdD-gB8KfOLoiTI+j4ANB18yIr+yHs5UBBgSRQECkJ5DJjPehvQSfJSzMgAegRAE1sJJkAg4CC8NgjAALYDoZDcSSiMAEomE5BYkDYewhLG+EAQehEyRsTboIkmcDAVYoeZ0OYLJbIFbrTbDZC7fZ9c6DAynOUDabDG71O6ix6QvDQj5fAK-Sj-QHAsEGZAAflBOqaxlMet4n2QTG14OYcFYEEdsLIinYQA

πŸ’» Code

`
interface IsLoading {
loaded: false;
obj: object | undefined;
}
interface Loaded {
loaded: true;
obj: object;
}
type MaybeLoaded = IsLoading | Loaded;

interface IsLoading2 {
loaded2: false;
obj: object | undefined;
}
interface Loaded2 {
loaded2: true;
obj: object;
}
type MaybeLoaded2 = IsLoading2 | Loaded2;

const sample = (ml: MaybeLoaded): MaybeLoaded2 => {
const { loaded, obj } = ml;
return { loaded2: loaded, obj };
};

//You can do this but this is annoying and needs useless runtime code
const sample2 = (ml: MaybeLoaded): MaybeLoaded2 => {
const { loaded, obj } = ml;
return loaded ? { loaded2: true, obj } : { loaded2: false, obj };
};
`

πŸ™ Actual behavior

There's an error mapping MaybeLoading to MaybeLoading2

πŸ™‚ Expected behavior

Both of these discriminated unions are structurally the same and should be "mappable" without having to cast using 'as' or writing needless runtime code

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions