TypeScript Master (50 Qs)•Part 1: Basic & Foundational TypeScript (Junior / Entry-Level)
What are Discriminated Unions (Tagged Unions)?
junior LevelCode ExampleTypeScript
In Simple Words:
A pattern where multiple object types share a common, unique literal property (the "discriminant" or "tag"). TypeScript automatically narrows the union inside a switch or if block:
typescript
interface LoadingState { state: "loading"; }
interface SuccessState { state: "success"; response: string[]; }
interface ErrorState { state: "error"; error: Error; }
type NetworkState = LoadingState | SuccessState | ErrorState;
function handleResponse(res: NetworkState) {
switch (res.state) {
case "loading":
return "Loading spinner...";
case "success":
return `Loaded ${res.response.length} items`; // Safe! TS knows res has response
case "error":
return `Failed: ${res.error.message}`; // Safe! TS knows res has error
}
}