Open this example in the interactive library
Source code
type State =
| { phase: "idle" }
| { phase: "loading"; id: number }
| { phase: "ready"; text: string }
| { phase: "error"; reason: string };
console.log(
((s: State, id: number): State =>
s.phase === "idle" ? { phase: "loading", id } : s)({ phase: "idle" }, 4),
);
Sample output
{ phase: 'loading', id: 4 }