Let's break this down simply
Type narrowing is how TypeScript pins a broad type down to a more specific one based on a runtime check. In a discriminated union, giving every branch a shared literal field means each branch can only access the properties that are actually valid for it.
typescript
type Result =
| { status: 'success'; data: string[] }
| { status: 'error'; message: string }
function render(result: Result): string {
switch (result.status) {
case 'success':
return `Found ${result.data.length} items`
case 'error':
return `Error: ${result.message}`
}
}
console.log(render({ status: 'success', data: ['Vue', 'TypeScript'] }))You should see
Found 2 itemsTry it yourself
Build a discriminated union of Circle and Rectangle, and write a function that calculates the area for each shape.
TypeScript Handbook — Narrowing — TypeScript