Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

TS
TypeScript
0/10 completed
Beginner
Why TypeScript?Basic types and inferenceTyping functionsObjects, interfaces and type aliases
Intermediate
Unions and narrowingLiteral types, tuples and enumsGenerics
Advanced
Utility typesMapped and conditional types
Pro
TypeScript in real projects
Tracks / TypeScript / Intermediate

Unions and narrowing

Real data comes in more than one shape: an ID might be a number or a string, an API call might succeed or fail. Union types describe "this OR that", and narrowing lets TypeScript know which one you have.

Union types: A | B

TypeScript · editable

With a union, you can only use what all members share, until you narrow it down.

Narrowing with typeof

TypeScript · editable

TypeScript follows your if, return, switch and && logic and narrows the type inside each branch. This is called control-flow analysis.

Handling null and undefined

With strict mode on (always turn it on!), null and undefined are not allowed unless you say so. This eliminates the most common JavaScript crash, "Cannot read properties of undefined":

TypeScript · editable

Other narrowing techniques

TypeScript · editable

Discriminated unions: the most useful pattern in TypeScript

Give every member of a union a shared literal property (often called type, kind or status). Checking it narrows to the exact member:

TypeScript · editable

This makes impossible states impossible: you can't have data while status is 'error'. Redux actions, API results and UI state machines all use this pattern.

Exhaustiveness checking with never

What if someone adds a new status later and forgets to handle it? Make the compiler catch it:

TypeScript · editable

Add a case 'triangle' and the error disappears.

Custom type guards

Write your own narrowing function with value is Type:

TypeScript · editable

Practice

Model the result of a payment as a discriminated union, with 'paid' (amount, receiptId), 'declined' (reason) and 'pending' (retryInSeconds). Write paymentMessage(result) using a switch with an exhaustive never check.

TypeScript · editable
✎ Check your understanding

1.Given value: string | number, what does if (typeof value === 'string') { ... } do?

2.What makes a union "discriminated"?

← Objects, interfaces and type aliases