You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//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
The text was updated successfully, but these errors were encountered:
If you really care about convincing the compiler to see what you're doing as safe, there's the approach at #47109 to switch to generic indexing. But that's not a natural refactoring for many cases, and because your discriminant type is not a valid key type it's even worse since we'd have to make up keys and you lose some inference you might want. It could look like this (using 0 and 1 as the dummy keys):
π Search Terms
discriminated union destructuring
π Version & Regression Information
β― 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
The text was updated successfully, but these errors were encountered: