-
Notifications
You must be signed in to change notification settings - Fork 0
Discriminated Unions
Jorge Castro edited this page Nov 10, 2025
·
1 revision
type State = {
status: "loading" | "success" | "error";
error?: Error;
data?: Array<{ id: number; name: string }>;
};const state1: State = {
status: "loading",
};
const state2: State = {
status: "success",
data: [{ id: 1, name: "Jane" }, { id: 2, name: "John" }],
};
const state3: State = {
status: "error",
error: new Error("The task failed successfully"),
};// The data has been fetched, but the status is still "loading"
const state4: State = {
status: "loading",
data: [{ id: 1, name: "Jane" }, { id: 2, name: "John" }],
};
// The status is "success", but there is an error present
const state5: State = {
status: "success",
error: new Error("The task failed successfully"),
};
// The status is "error", but there is no error object
const state6: State = {
status: "error",
};Invalid combinations like in Example 2 are now caught by the type system:
type State =
| { status: "loading" }
| { status: "success"; data: Array<{ id: number; name: string }> }
| { status: "error"; error: Error };- Sync-Obsidian-with-GitHub-on-iOS
- Obsidian-community-plugins
- Optimizing-Novel-Word-Count-Plugin-for-Git-Users
- What is TypeScript, and why you should use it
- Quick setup
- Inference and type annotations
- Fundamental Types
- Object Types
- Union Types
- Type Aliases and Interfaces
- Type Assertions
- Literal Types
- null and undefined
- Narrowing
- Creating Types from Types
- Common Built‐in and Utility Types
- tsc CLI ‐ (The Compiler)
- Avoid using Object or {}
- Ignoring TypeScript errors
- TypeScript resources