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, text: string): State =>
s.phase === "loading" ? { phase: "ready", text } : s)(
{ phase: "loading", id: 1 },
"done",
),
);
Sample output
{ phase: 'ready', text: 'done' }