Series: TypeScript from Basics to Advanced
Part: 7 — Type Narrowing & Type Guards
Level: Beginner → Intermediate
Introduction
In the previous part, we learned about Union and Intersection Types.
For example:
let id: string | number;
This tells TypeScript:
idcan be a string OR a number.
But now we have an important problem.
If id can be either a string or a number, how do we safely determine which one it is?
For example:
function printId(id: string | number) {
// Is id a string?
// Or is it a number?
}
This is where Type Narrowing comes in.
Type narrowing allows TypeScript to determine a more specific type based on conditions in your code.
Type guards are the techniques we use to perform this narrowing.
In this article, we'll learn:
-
What type narrowing means
-
Why type narrowing is necessary
-
typeof -
instanceof -
The
inoperator -
Equality narrowing
-
Truthiness narrowing
-
Custom type guards
-
Type predicates
-
Discriminated unions
-
Exhaustive checking with
never -
Real-world API examples
-
React examples
-
Common mistakes
-
Best practices
1. What Is Type Narrowing?
Type narrowing means taking a broad type and making it more specific based on the information available in your code.
Consider:
function printValue(value: string | number) {
console.log(value);
}
At the beginning of the function:
value → string | number
Now we check:
if (typeof value === "string") {
console.log(value.toUpperCase());
}
Inside the if block, TypeScript knows:
value → string
Outside that block, it may still be:
value → string | number
This process is called type narrowing.
2. Why Do We Need Type Narrowing?
Suppose we have:
function formatValue(value: string | number) {
return value.toUpperCase();
}
TypeScript gives an error.
Why?
Because number doesn't have:
toUpperCase()
The value could be:
"hello"
or:
100
We first need to determine the actual type.
function formatValue(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
Now TypeScript understands what each branch contains.
3. typeof Type Guard
The most common type guard is typeof.
JavaScript provides the typeof operator, and TypeScript uses it for type narrowing.
For example:
function processValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
TypeScript understands:
if typeof value === "string"
↓
value is string
and:
else
↓
value is number
4. Common typeof Checks
You can use typeof with several JavaScript types.
typeof value === "string"
typeof value === "number"
typeof value === "boolean"
typeof value === "bigint"
typeof value === "symbol"
typeof value === "function"
You can also check:
typeof value === "undefined"
5. typeof with Functions
Consider:
function execute(
callback: (() => void) | string
) {
if (typeof callback === "function") {
callback();
} else {
console.log(callback);
}
}
Inside the first branch, TypeScript knows callback is a function.
This allows:
callback();
without an error.
6. instanceof Type Guard
instanceof is useful when working with classes and objects created from constructors.
For example:
class User {
constructor(public name: string) {}
}
class Admin {
constructor(public permissions: string[]) {}
}
Now:
function printAccount(account: User | Admin) {
if (account instanceof User) {
console.log(account.name);
} else {
console.log(account.permissions);
}
}
TypeScript understands:
account instanceof User
↓
account is User
Otherwise:
account is Admin
7. When Should You Use instanceof?
instanceof is particularly useful when your application uses classes.
For example:
class ApiError extends Error {
statusCode: number;
constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
}
}
Now:
try {
// API request
} catch (error) {
if (error instanceof ApiError) {
console.log(error.statusCode);
}
}
TypeScript can understand that error is an ApiError inside the condition.
8. The in Operator
The in operator is useful when different object types have different properties.
Consider:
type Admin = {
name: string;
permissions: string[];
};
type User = {
name: string;
email: string;
};
type Account = Admin | User;
We can check whether a property exists:
function printAccount(account: Account) {
if ("permissions" in account) {
console.log(account.permissions);
} else {
console.log(account.email);
}
}
TypeScript understands that an object containing permissions must be an Admin.
9. Why Is in Useful?
The in operator is useful when your union types don't have an obvious discriminator.
For example:
type Car = {
brand: string;
wheels: number;
};
type Boat = {
brand: string;
propeller: number;
};
We can write:
function move(vehicle: Car | Boat) {
if ("wheels" in vehicle) {
console.log("Moving on the road");
} else {
console.log("Moving on water");
}
}
The property itself becomes the clue TypeScript uses to narrow the type.
10. Equality Narrowing
TypeScript can also narrow types using equality checks.
For example:
function printValue(
value: string | number
) {
if (value === "hello") {
console.log("It's hello");
}
}
Inside the condition, TypeScript knows that:
value → "hello"
This becomes especially useful with literal unions.
11. Equality with Two Variables
TypeScript can sometimes narrow both variables based on equality.
For example:
function compare(
a: string | number,
b: string | number
) {
if (a === b) {
console.log(a);
console.log(b);
}
}
Inside the equality branch, TypeScript can use the fact that both values have the same runtime value to narrow their types appropriately.
Equality checks are especially useful when dealing with discriminated unions.
12. Truthiness Narrowing
TypeScript can narrow values based on whether they are truthy or falsy.
For example:
function printName(name: string | null) {
if (name) {
console.log(name.toUpperCase());
}
}
Inside the if block, TypeScript knows:
name → string
because null is falsy.
Another example:
function processValue(value: string | undefined) {
if (value) {
console.log(value.length);
}
}
Inside the block:
value → string
13. Be Careful with Truthiness
Truthiness narrowing can sometimes produce unexpected results.
Consider:
function printNumber(value: number | null) {
if (value) {
console.log(value);
}
}
This will not execute when:
value = 0;
because 0 is falsy in JavaScript.
If 0 is a valid value and you specifically want to check for null, use:
if (value !== null) {
console.log(value);
}
This is more precise.
14. Narrowing with null and undefined
You can explicitly check for missing values.
function printUser(user: User | null) {
if (user !== null) {
console.log(user.name);
}
}
For undefined:
function printName(name: string | undefined) {
if (name !== undefined) {
console.log(name.toUpperCase());
}
}
You can also use:
if (value != null) {
// value is not null or undefined
}
The loose inequality check against null is a common JavaScript pattern that TypeScript understands for narrowing both null and undefined.
15. Discriminated Unions
Discriminated unions are one of the most powerful applications of type narrowing.
Suppose we have:
type SuccessResponse = {
status: "success";
data: User;
};
type ErrorResponse = {
status: "error";
message: string;
};
type ApiResponse =
| SuccessResponse
| ErrorResponse;
We can narrow using status:
function handleResponse(response: ApiResponse) {
if (response.status === "success") {
console.log(response.data);
} else {
console.log(response.message);
}
}
This works because status is the discriminant property.
16. Discriminated Unions with switch
A switch statement is often very readable for discriminated unions.
type TestState =
| {
status: "not-started";
}
| {
status: "in-progress";
questionNumber: number;
}
| {
status: "completed";
score: number;
};
Now:
function showTestState(state: TestState) {
switch (state.status) {
case "not-started":
console.log("Start the test");
break;
case "in-progress":
console.log(state.questionNumber);
break;
case "completed":
console.log(state.score);
break;
}
}
TypeScript automatically narrows state in each case.
17. Custom Type Guards
Sometimes TypeScript's built-in type guards aren't enough.
You can create your own.
Consider:
type User = {
name: string;
email: string;
};
We can create a function:
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
"email" in value
);
}
The important part is:
value is User
This is called a type predicate.
It tells TypeScript:
If this function returns
true, treatvalueas aUser.
18. Using a Custom Type Guard
Now we can safely use:
function processData(data: unknown) {
if (isUser(data)) {
console.log(data.name);
console.log(data.email);
}
}
Before the check:
data → unknown
After:
if (isUser(data)) {
TypeScript knows:
data → User
This is especially useful when working with external data.
19. Why unknown and Type Guards Work Together
Remember from Part 2 that unknown is safer than any.
Suppose we receive data from an API:
const data: unknown = await response.json();
We shouldn't immediately assume:
const user = data as User;
Instead, validate the structure.
if (isUser(data)) {
console.log(data.name);
}
This makes the application more defensive around untrusted data.
20. Type Predicate Syntax
The general syntax is:
function functionName(
value: unknown
): value is SomeType {
// validation
}
For example:
function isString(value: unknown): value is string {
return typeof value === "string";
}
Now:
function printValue(value: unknown) {
if (isString(value)) {
console.log(value.toUpperCase());
}
}
The custom function tells TypeScript exactly what type the value has when the function returns true.
21. Custom Type Guard for Admin
Consider:
type User = {
name: string;
email: string;
};
type Admin = {
name: string;
permissions: string[];
};
We can write:
function isAdmin(
account: User | Admin
): account is Admin {
return "permissions" in account;
}
Now:
function printAccount(account: User | Admin) {
if (isAdmin(account)) {
console.log(account.permissions);
} else {
console.log(account.email);
}
}
This makes complex type checks reusable.
22. Type Guards with Arrays
Custom type guards can also be useful with arrays.
Suppose:
const values: unknown[] = [
"JavaScript",
10,
"TypeScript",
true
];
We can create:
function isString(value: unknown): value is string {
return typeof value === "string";
}
Then:
const strings = values.filter(isString);
TypeScript can infer:
strings → string[]
This is a very useful pattern.
23. Narrowing with Array.isArray()
JavaScript provides Array.isArray().
TypeScript understands it as a type guard.
function processData(
data: string | string[]
) {
if (Array.isArray(data)) {
console.log(data.length);
} else {
console.log(data.toUpperCase());
}
}
Inside the first branch:
data → string[]
Inside the else:
data → string
24. Narrowing with typeof and Array.isArray
You can combine multiple checks.
function processValue(
value: string | number | string[]
) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else if (Array.isArray(value)) {
console.log(value.join(", "));
} else {
console.log(value.toFixed(2));
}
}
TypeScript progressively narrows the type.
This is called control-flow analysis.
25. Control-Flow Analysis
TypeScript doesn't just look at one condition.
It follows the flow of your program.
For example:
function process(value: string | number | null) {
if (value === null) {
return;
}
if (typeof value === "string") {
console.log(value.toUpperCase());
return;
}
console.log(value.toFixed(2));
}
TypeScript understands:
After:
if (value === null) {
return;
}
value is no longer null.
After:
if (typeof value === "string") {
the remaining possibility is number.
So the final line can safely use:
value.toFixed(2);
26. The never Type and Exhaustive Checks
Type narrowing works especially well with never.
Consider:
type Status =
| "pending"
| "success"
| "failed";
We can create:
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
Then:
function handleStatus(status: Status) {
switch (status) {
case "pending":
return "Waiting";
case "success":
return "Completed";
case "failed":
return "Failed";
default:
return assertNever(status);
}
}
If someone later adds:
"cancelled"
to Status but forgets to add a case, TypeScript can report an error at the assertNever(status) call.
This helps catch incomplete logic during development.
27. Real-World API Example
Imagine your backend can return three different states:
type ApiResponse =
| {
status: "success";
data: User;
}
| {
status: "error";
message: string;
}
| {
status: "loading";
};
We can handle it safely:
function handleApiResponse(
response: ApiResponse
) {
switch (response.status) {
case "loading":
console.log("Loading...");
break;
case "success":
console.log(response.data.name);
break;
case "error":
console.log(response.message);
break;
}
}
Each branch gets access only to the properties that actually exist for that state.
28. React Example
Type narrowing is extremely useful in React applications.
Consider component props:
type Props =
| {
type: "image";
src: string;
alt: string;
}
| {
type: "video";
src: string;
duration: number;
};
Now:
function Media(props: Props) {
if (props.type === "image") {
return <img src={props.src} alt={props.alt} />;
}
return (
<video src={props.src}>
{props.duration}
</video>
);
}
When:
props.type === "image"
TypeScript knows that:
props.alt
exists.
When the type is "video", TypeScript knows:
props.duration
exists.
This is one of the best patterns for designing type-safe React components.
29. Authentication Example
Consider authentication state:
type AuthState =
| {
status: "logged-out";
}
| {
status: "logged-in";
user: User;
};
Now:
function AuthStatus(state: AuthState) {
if (state.status === "logged-in") {
console.log(state.user.name);
} else {
console.log("Please log in");
}
}
You don't need optional properties like:
user?: User;
The type itself describes whether the user exists.
30. Type Narrowing vs Type Assertion
These concepts are often confused.
Type narrowing
TypeScript determines the type based on actual conditions.
function print(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
Here TypeScript has evidence that value is a string.
Type assertion
You tell TypeScript what you believe the type is.
const value = data as User;
You're saying:
Trust me, this value is a User.
Type assertion does not perform runtime validation.
That's why narrowing is generally safer when you can actually check the value.
31. Common Mistakes
Mistake 1: Using as Everywhere
Avoid:
const user = data as User;
when you don't actually know whether data is a User.
Prefer validating or narrowing the value.
Mistake 2: Using any
Avoid:
function process(data: any) {
console.log(data.name);
}
You lose useful type checking.
Prefer:
function process(data: unknown) {
if (isUser(data)) {
console.log(data.name);
}
}
Mistake 3: Using Truthiness When Zero Is Valid
Avoid:
if (score) {
console.log(score);
}
if 0 is a valid score.
Prefer:
if (score !== null) {
console.log(score);
}
when the actual condition you're interested in is null.
Mistake 4: Forgetting null
This can be dangerous:
function printUser(user: User | null) {
console.log(user.name);
}
user could be null.
Instead:
function printUser(user: User | null) {
if (user !== null) {
console.log(user.name);
}
}
Mistake 5: Writing Complex Checks Everywhere
If you repeatedly write:
"permissions" in account
throughout your application, consider creating:
function isAdmin(
account: User | Admin
): account is Admin {
return "permissions" in account;
}
Now your code becomes easier to read and maintain.
32. Best Practices
1. Prefer narrowing over unnecessary type assertions
Use runtime information whenever possible.
2. Use discriminated unions for application states
For example:
status: "loading"
status: "success"
status: "error"
3. Use unknown for untrusted data
Then narrow it before using it.
4. Create reusable custom type guards
If the same check appears multiple times, turn it into a function.
5. Use precise conditions
Prefer:
value !== null
over truthiness checks when 0, false, or "" are valid values.
6. Use exhaustive checks for important state machines
The never pattern can help detect newly added states that haven't been handled.
Type Narrowing Cheat Sheet
Remember these common techniques:
typeof
typeof value === "string"
Useful for primitive types and functions.
instanceof
value instanceof MyClass
Useful for class instances.
in
"property" in value
Useful for distinguishing object shapes.
Equality checks
value === "success"
Useful for literal and discriminated unions.
Null checks
value !== null
Useful for nullable values.
Array checks
Array.isArray(value)
Useful for distinguishing arrays from other values.
Custom type guard
value is User
Useful for reusable application-specific checks.
Final Takeaway
Type narrowing is how TypeScript moves from a broad type to a more specific type based on the logic in your program.
For example:
string | number
starts as two possibilities.
After:
typeof value === "string"
TypeScript knows:
value → string
The most important techniques to remember are:
typeof
instanceof
in
=== / !==
Array.isArray()
and custom type guards:
value is User
Type narrowing becomes especially powerful when combined with:
-
Union types
-
Literal types
-
Discriminated unions
-
unknown -
Custom type guards
-
never
These features allow TypeScript to model real-world application logic much more accurately.