Mamun Labs Learn
JourneyGlossary
esc
  • Try “map”, “flexbox” or “state”.
Log in
Start learning
Phase 4 · 4 / 5Unions and optional values
Phase 4TypeScript
5 topics · 2 wks
  1. 1Why types catch bugs
  2. 2Reading type annotations
  3. 3Types for objects
  4. 4Unions and optional values
  5. 5Reading type errors
JourneyPhase 4Unions and optional values
01 / 09Overview

Unions and optional values

You'll learn to read | (one of several types), ? (a field that may be missing), and why TypeScript makes you check for undefined.

Why it mattersReal data is often missing: no phone number, a find that finds nothing. Most crashes in apps come from that, and these types point at it.
about 60 min·needs: Types for objects, Making decisions with if, filter and find
02 / 09

Watch & read

Start with the required ones. The others are there when you need them.

Docs
Everyday types, union typesTypeScript Handbook (official) · 15 min · English
MMamun's noteRead "Union Types" (both parts), then jump to "Literal Types" and "null and undefined". Go back up and read "Optional Properties" too. Skip "Type Assertions" and the ! operator; it hides errors instead of fixing them.
Video
Learn TypeScript, full course for beginners (literal types, unions, narrowing)YouTube · freeCodeCamp (Bob Ziroll, Scrimba) · 19 min · English
MMamun's noteWatch 56:13–1:12:39: literal types, unions, an order status made from a union, and type narrowing. If you have 3 more minutes, also watch 43:15–45:58 on optional properties.
DocsOptional
NarrowingTypeScript Handbook (official) · 10 min · English
MMamun's noteRead the intro, "typeof type guards", "Truthiness narrowing" and "Equality narrowing". Stop there; the rest is for later.
VideoOptional
Lesson 4: Explicit & union types, TypeScript Bangla tutorial seriesYouTube · Learn with Sumit · 10 min · Bangla
MMamun's noteIn Bangla. Sumit shows how to write a type yourself and how | lets a value be one of several types.
03 / 09

Explanation

An order's payment can be pending, paid or failed. Nothing else. And some customers give a phone number, some don't. You want the types to say both things, so TypeScript can check every place that uses them.

The | means "or". A type made with | is called a union type.

type Status = "pending" | "paid" | "failed";
let code: string | number = "A12";

Status allows exactly three strings. A single exact value used as a type, like "paid", is called a literal type. If you write "shipped", you get Type '"shipped"' is not assignable to type 'Status'. It is like the options on a bKash screen: you can only tap the buttons that are there.

A ? after a field name means the field may be missing. It is an optional property.

type Order = {
id: number;
status: Status;
phone?: string;
};

phone?: string means phone is a string or undefined. So when you use it, TypeScript stops you:

order.phone.length
// 'order.phone' is possibly 'undefined'.

In plain JavaScript, this line crashes with Cannot read properties of undefined the first time a customer has no phone. TypeScript shows it before that day comes. The fix is to check first:

if (order.phone === undefined) {
return "No phone";
}
return order.phone.slice(0, 3); // safe: phone is a string here

After the if, TypeScript knows phone can't be undefined any more. This is called narrowing: a check makes the type smaller. You'll see the same thing with find, which gives back Student | undefined, because it may find nothing.

People often (and AI very often) make the red line go away by adding !, as in order.phone!.length. That only tells TypeScript "trust me". It doesn't check anything, and the app still crashes when phone is missing. Add a real check instead.

When you read a type, look for | and ?. Each one means "this might be something else", so look for the if that handles the other case.

Words to recognise
union type|literal typeoptional property?narrowingpossibly undefined
04 / 09

Code tour

Click a line number with a ring to read the note for that line.

app.ts5 notes
type Status = "pending" | "paid" | "failed";
Mentor note · line 1
A union of three literal types. Read | as "or": a Status is "pending" or "paid" or "failed", and nothing else.
2
3type Order = {
4 id: number;
status: Status;
phone?: string;
7};
8
9function contact(order: Order): string {
if (order.phone === undefined) {
11 return "No phone";
12 }
return "Call " + order.phone.slice(0, 3);
14}
05 / 09

Practice

Short drills. Take your time and read the code before you answer.

DrillPredict1 / 3
1type Order = { id: number; phone?: string };
2function digits(order: Order) {
3 return order.phone.length;
4}
What does TypeScript say?
DrillPredict2 / 3
1type Status = "pending" | "paid" | "failed";
2let payment: Status = "pending";
3payment = "paid";
4payment = "shipped";
Which line gets a red underline?
DrillHandle the missing phone3 / 3
In TypeScript, phone?: string would make order.phone.slice(...) show 'order.phone' is possibly 'undefined'. This is plain JavaScript, so you'll see the crash instead. phonePrefix should give the first 3 digits of the phone, or "none" when there is no phone. Fix it so all three checks pass.
1
2
3
Try 1 of 3 · solution unlocks after 3
06 / 09

Quick check

3 questions. Each one explains itself after you answer.

  1. 1 / 3In type Customer = { name: string; phone?: string }, what can phone be?
  2. 2 / 3const found = students.find(s => s.name === "Nusrat"); If students is Student[], what is the type of found?
  3. 3 / 3AI changes order.phone.length to order.phone!.length and the red line is gone. What happens when a customer has no phone?
07 / 09

Explain it back

Only you can see this. Log in to keep it.0 words
08 / 09

How confident are you with Unions and optional values?

09 / 09

Done

You can now
Read status: "pending" | "paid" and phone?: string, and fix code that TypeScript says is possibly 'undefined'.
Next: Reading type errors Back to Phase 4
On this page
  1. 01Unions and optional values
  2. 02Watch & read
  3. 03Explanation
  4. 04Code tour
  5. 05Practice
  6. 06Quick check
  7. 07Explain it back
  8. 08Confidence
  9. 09Done
Up next · 02 / 09Watch & read
Mamun Labs LearnFound a mistake on this page? Tell Mamun.
Mamun Labs Learn
JourneyGlossary
esc
  • Try “map”, “flexbox” or “state”.
Log in
Start learning
Log in to save your progress. Everything here works without an account.Log in to save progressLog in
Phase 4TypeScript
5 topics · 2 wks
  1. 1Why types catch bugs
  2. 2Reading type annotations
  3. 3Types for objects
  4. 4Unions and optional values
  5. 5Reading type errors
JourneyPhase 4Unions and optional values
01 / 09Overview

Unions and optional values

You'll learn to read | (one of several types), ? (a field that may be missing), and why TypeScript makes you check for undefined.

Why it mattersReal data is often missing: no phone number, a find that finds nothing. Most crashes in apps come from that, and these types point at it.
about 60 min·needs: Types for objects, Making decisions with if, filter and find
02 / 09

Watch & read

Start with the required ones. The others are there when you need them.

Docs
Everyday types, union typesTypeScript Handbook (official) · 15 min · English
MMamun's noteRead "Union Types" (both parts), then jump to "Literal Types" and "null and undefined". Go back up and read "Optional Properties" too. Skip "Type Assertions" and the ! operator; it hides errors instead of fixing them.
Video
Learn TypeScript, full course for beginners (literal types, unions, narrowing)YouTube · freeCodeCamp (Bob Ziroll, Scrimba) · 19 min · English
MMamun's noteWatch 56:13–1:12:39: literal types, unions, an order status made from a union, and type narrowing. If you have 3 more minutes, also watch 43:15–45:58 on optional properties.
DocsOptional
NarrowingTypeScript Handbook (official) · 10 min · English
MMamun's noteRead the intro, "typeof type guards", "Truthiness narrowing" and "Equality narrowing". Stop there; the rest is for later.
VideoOptional
Lesson 4: Explicit & union types, TypeScript Bangla tutorial seriesYouTube · Learn with Sumit · 10 min · Bangla
MMamun's noteIn Bangla. Sumit shows how to write a type yourself and how | lets a value be one of several types.
03 / 09

Explanation

An order's payment can be pending, paid or failed. Nothing else. And some customers give a phone number, some don't. You want the types to say both things, so TypeScript can check every place that uses them.

The | means "or". A type made with | is called a union type.

type Status = "pending" | "paid" | "failed";
let code: string | number = "A12";

Status allows exactly three strings. A single exact value used as a type, like "paid", is called a literal type. If you write "shipped", you get Type '"shipped"' is not assignable to type 'Status'. It is like the options on a bKash screen: you can only tap the buttons that are there.

A ? after a field name means the field may be missing. It is an optional property.

type Order = {
id: number;
status: Status;
phone?: string;
};

phone?: string means phone is a string or undefined. So when you use it, TypeScript stops you:

order.phone.length
// 'order.phone' is possibly 'undefined'.

In plain JavaScript, this line crashes with Cannot read properties of undefined the first time a customer has no phone. TypeScript shows it before that day comes. The fix is to check first:

if (order.phone === undefined) {
return "No phone";
}
return order.phone.slice(0, 3); // safe: phone is a string here

After the if, TypeScript knows phone can't be undefined any more. This is called narrowing: a check makes the type smaller. You'll see the same thing with find, which gives back Student | undefined, because it may find nothing.

People often (and AI very often) make the red line go away by adding !, as in order.phone!.length. That only tells TypeScript "trust me". It doesn't check anything, and the app still crashes when phone is missing. Add a real check instead.

When you read a type, look for | and ?. Each one means "this might be something else", so look for the if that handles the other case.

Words to recognise
union type|literal typeoptional property?narrowingpossibly undefined
04 / 09

Code tour

Click a line number with a ring to read the note for that line.

app.ts5 notes
type Status = "pending" | "paid" | "failed";
Mentor note · line 1
A union of three literal types. Read | as "or": a Status is "pending" or "paid" or "failed", and nothing else.
2
3type Order = {
4 id: number;
status: Status;
phone?: string;
7};
8
9function contact(order: Order): string {
if (order.phone === undefined) {
11 return "No phone";
12 }
return "Call " + order.phone.slice(0, 3);
14}
05 / 09

Practice

Short drills. Take your time and read the code before you answer.

DrillPredict1 / 3
1type Order = { id: number; phone?: string };
2function digits(order: Order) {
3 return order.phone.length;
4}
What does TypeScript say?
DrillPredict2 / 3
1type Status = "pending" | "paid" | "failed";
2let payment: Status = "pending";
3payment = "paid";
4payment = "shipped";
Which line gets a red underline?
DrillHandle the missing phone3 / 3
In TypeScript, phone?: string would make order.phone.slice(...) show 'order.phone' is possibly 'undefined'. This is plain JavaScript, so you'll see the crash instead. phonePrefix should give the first 3 digits of the phone, or "none" when there is no phone. Fix it so all three checks pass.
1
2
3
Try 1 of 3 · solution unlocks after 3
06 / 09

Quick check

3 questions. Each one explains itself after you answer.

  1. 1 / 3In type Customer = { name: string; phone?: string }, what can phone be?
  2. 2 / 3const found = students.find(s => s.name === "Nusrat"); If students is Student[], what is the type of found?
  3. 3 / 3AI changes order.phone.length to order.phone!.length and the red line is gone. What happens when a customer has no phone?
07 / 09

Explain it back

Only you can see this. Log in to keep it.0 words
08 / 09

How confident are you with Unions and optional values?

09 / 09

Done

You can now
Read status: "pending" | "paid" and phone?: string, and fix code that TypeScript says is possibly 'undefined'.
Next: Reading type errors Back to Phase 4
On this page
  1. 01Unions and optional values
  2. 02Watch & read
  3. 03Explanation
  4. 04Code tour
  5. 05Practice
  6. 06Quick check
  7. 07Explain it back
  8. 08Confidence
  9. 09Done
Up next · 02 / 09Watch & read

An order's payment can be pending, paid or failed. Nothing else. And some customers give a phone number, some don't. You want the types to say both things, so TypeScript can check every place that uses them.

The | means "or". A type made with | is called a union type.

type Status = "pending" | "paid" | "failed";
let code: string | number = "A12";

Status allows exactly three strings. A single exact value used as a type, like "paid", is called a literal type. If you write "shipped", you get Type '"shipped"' is not assignable to type 'Status'. It is like the options on a bKash screen: you can only tap the buttons that are there.

A ? after a field name means the field may be missing. It is an optional property.

type Order = {
id: number;
status: Status;
phone?: string;
};

phone?: string means phone is a string or undefined. So when you use it, TypeScript stops you:

order.phone.length
// 'order.phone' is possibly 'undefined'.

In plain JavaScript, this line crashes with Cannot read properties of undefined the first time a customer has no phone. TypeScript shows it before that day comes. The fix is to check first:

if (order.phone === undefined) {
return "No phone";
}
return order.phone.slice(0, 3); // safe: phone is a string here

After the if, TypeScript knows phone can't be undefined any more. This is called narrowing: a check makes the type smaller. You'll see the same thing with find, which gives back Student | undefined, because it may find nothing.

People often (and AI very often) make the red line go away by adding !, as in order.phone!.length. That only tells TypeScript "trust me". It doesn't check anything, and the app still crashes when phone is missing. Add a real check instead.

When you read a type, look for | and ?. Each one means "this might be something else", so look for the if that handles the other case.

Words to recognise
union type|literal typeoptional property?narrowingpossibly undefined

An order's payment can be pending, paid or failed. Nothing else. And some customers give a phone number, some don't. You want the types to say both things, so TypeScript can check every place that uses them.

The | means "or". A type made with | is called a union type.

type Status = "pending" | "paid" | "failed";
let code: string | number = "A12";

Status allows exactly three strings. A single exact value used as a type, like "paid", is called a literal type. If you write "shipped", you get Type '"shipped"' is not assignable to type 'Status'. It is like the options on a bKash screen: you can only tap the buttons that are there.

A ? after a field name means the field may be missing. It is an optional property.

type Order = {
id: number;
status: Status;
phone?: string;
};

phone?: string means phone is a string or undefined. So when you use it, TypeScript stops you:

order.phone.length
// 'order.phone' is possibly 'undefined'.

In plain JavaScript, this line crashes with Cannot read properties of undefined the first time a customer has no phone. TypeScript shows it before that day comes. The fix is to check first:

if (order.phone === undefined) {
return "No phone";
}
return order.phone.slice(0, 3); // safe: phone is a string here

After the if, TypeScript knows phone can't be undefined any more. This is called narrowing: a check makes the type smaller. You'll see the same thing with find, which gives back Student | undefined, because it may find nothing.

People often (and AI very often) make the red line go away by adding !, as in order.phone!.length. That only tells TypeScript "trust me". It doesn't check anything, and the app still crashes when phone is missing. Add a real check instead.

When you read a type, look for | and ?. Each one means "this might be something else", so look for the if that handles the other case.

Words to recognise
union type|literal typeoptional property?narrowingpossibly undefined