Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Type Narrowing

Learn how TypeScript narrows a variable from multiple possible types to a more specific type using conditions, type checks and control flow.

Simple Explanation: Type Narrowing means checking a value's type before using it. It helps TypeScript identify which properties and methods are safe to access at a particular point in your code.

1. What is Type Narrowing?

A variable can have more than one possible type, such as string | number. Before calling a string-specific method, TypeScript needs to know that the current value is a string.

Type Narrowing uses conditions and type checks to reduce the possible types of a value within a specific code branch.

Basic Example

function displayValue(value: string | number): void {
    if (typeof value === "string") {
        console.log(value.toUpperCase());
    } else {
        console.log(value * 2);
    }
}

displayValue("hello");
displayValue(10);

Expected Output

HELLO
20

Inside the first branch, TypeScript knows that value is a string. Inside the else branch, it knows that value is a number.

2. Type Narrowing Workflow Diagram

Follow this diagram to understand how a type check helps TypeScript determine the current type of a value.

📥
Receive Value

A variable may have multiple possible types.

→
🔍
Check Condition

Use typeof, instanceof, in or another valid check.

→
🎯
Narrow Type

TypeScript identifies the type supported by the branch.

→
✅
Use Safely

Access properties and methods valid for that type.

Remember: Type Narrowing is based on control flow. TypeScript tracks conditions, assignments and other checks to determine which types remain possible at a given point in the code.

3. Type Narrowing with typeof

The typeof operator checks the runtime type category of a value. TypeScript uses this check to narrow types such as strings and numbers.

Example

function processInput(value: string | number): void {
    if (typeof value === "string") {
        console.log("String length: " + value.length);
    } else {
        console.log("Number squared: " + value * value);
    }
}

processInput("TypeScript");
processInput(5);

Expected Output

String length: 10
Number squared: 25

Common typeof Results

Value typeof Result
"Hello" "string"
100 "number"
true "boolean"
undefined "undefined"
10n "bigint"
Symbol("id") "symbol"
Important: In JavaScript, typeof null returns "object". For null checks, use value === null.

4. Truthiness Narrowing

A truthiness check uses a value directly in an if condition. This can remove falsy values such as empty strings, zero, false, null and undefined from the truthy branch.

Example

function printName(name: string | null): void {
    if (name) {
        console.log("Name: " + name.toUpperCase());
    } else {
        console.log("Name is missing");
    }
}

printName("Rahul");
printName(null);
printName("");

Expected Output

Name: RAHUL
Name is missing
Name is missing

The truthy branch receives a non-empty string in this example. The else branch runs for null and the empty string.

Tip: A truthiness check also rejects valid values such as 0 and an empty string. When those values are valid data, use an explicit check such as value !== undefined or value !== null.

5. Equality Narrowing

Equality checks such as === and !== can narrow types. Comparing a value with a specific literal can help TypeScript identify which union member is currently possible.

Example

function displayStatus(status: "active" | "inactive"): void {
    if (status === "active") {
        console.log("User is active");
    } else {
        console.log("User is inactive");
    }
}

displayStatus("active");
displayStatus("inactive");

Expected Output

User is active
User is inactive

After checking whether status equals "active", TypeScript knows the value is "active" in the if branch and "inactive" in the else branch.

6. Type Narrowing with the in Operator

The in operator checks whether a property exists on an object or within its prototype chain. TypeScript can use this check to narrow a union of object types when the property distinguishes those types.

Example: Student and Teacher

type Student = {
    name: string;
    course: string;
};

type Teacher = {
    name: string;
    subject: string;
};

function displayPerson(person: Student | Teacher): void {
    console.log("Name: " + person.name);

    if ("course" in person) {
        console.log("Course: " + person.course);
    } else {
        console.log("Subject: " + person.subject);
    }
}

displayPerson({
    name: "Rahul",
    course: "TypeScript"
});

displayPerson({
    name: "Priya",
    subject: "Programming"
});

Expected Output

Name: Rahul
Course: TypeScript
Name: Priya
Subject: Programming

Workflow Diagram

📦
Student | Teacher

The value may have either object structure.

→
🔍
Check "course"

Determine whether the course property exists.

→
✅
Narrowed Object

Use course for Student or subject for Teacher.

7. Type Narrowing with instanceof

The instanceof operator checks whether an object is an instance of a particular class or constructor. TypeScript can use the result to narrow the type within a condition.

Example

class Dog {
    bark(): void {
        console.log("Dog is barking");
    }
}

class Cat {
    meow(): void {
        console.log("Cat says meow");
    }
}

function makeSound(animal: Dog | Cat): void {
    if (animal instanceof Dog) {
        animal.bark();
    } else {
        animal.meow();
    }
}

makeSound(new Dog());
makeSound(new Cat());

Expected Output

Dog is barking
Cat says meow

When the condition is true, TypeScript narrows animal to Dog. Otherwise, the remaining type in this example is Cat.

8. Custom Type Guards

A custom type guard is a function whose return type uses a type predicate such as value is string. It allows TypeScript to narrow a value when the function returns true.

Example

function isString(value: string | number): value is string {
    return typeof value === "string";
}

function displayValue(value: string | number): void {
    if (isString(value)) {
        console.log(value.toUpperCase());
    } else {
        console.log(value.toFixed(2));
    }
}

displayValue("hello");
displayValue(25);

Expected Output

HELLO
25.00

Custom Type Guard Workflow

🛠️
Type Guard Function

Checks the actual value and returns a boolean.

→
🎯
Type Predicate

Tells TypeScript what the true result means.

→
✅
Narrowed Value

The caller can use the specific type in the true branch.

Important: The type predicate does not verify that the implementation is correct. Your guard function must perform a check that genuinely supports the type it claims to identify.

9. Discriminated Unions

A discriminated union combines object types that share a common property with different literal values. TypeScript uses that property to determine which object type is currently being handled.

Example: API Result

type ApiResult =
    | { status: "success"; data: string }
    | { status: "error"; message: string };

function handleResult(result: ApiResult): void {
    if (result.status === "success") {
        console.log("Data: " + result.data);
    } else {
        console.log("Error: " + result.message);
    }
}

handleResult({
    status: "success",
    data: "Student loaded"
});

handleResult({
    status: "error",
    message: "Student not found"
});

Expected Output

Data: Student loaded
Error: Student not found

Discriminated Union Diagram

📦
ApiResult

Can represent success or error.

✅
Success

status: "success"

data: string

❌
Error

status: "error"

message: string

Checking the status property tells TypeScript which fields are available. A success result has data; an error result has message.

10. Narrowing null and undefined

TypeScript can narrow nullable values by checking whether a value is null or undefined before accessing it.

Example

function displayMessage(message: string | null | undefined): void {
    if (message === null || message === undefined) {
        console.log("No message available");
        return;
    }

    console.log(message.toUpperCase());
}

displayMessage("Welcome");
displayMessage(null);
displayMessage(undefined);

Expected Output

WELCOME
No message available
No message available

After the null and undefined checks return, TypeScript knows the remaining message value is a string.

11. Exhaustive Checking with never

The never type can help identify unhandled cases in a discriminated union. If a new union member is added later, exhaustive checking can help reveal that a branch is missing.

Example

type Shape =
    | { kind: "circle"; radius: number }
    | { kind: "square"; side: number };

function getArea(shape: Shape): number {
    switch (shape.kind) {
        case "circle":
            return Math.PI * shape.radius * shape.radius;

        case "square":
            return shape.side * shape.side;

        default: {
            const exhaustiveCheck: never = shape;
            return exhaustiveCheck;
        }
    }
}

console.log(getArea({
    kind: "circle",
    radius: 2
}));

console.log(getArea({
    kind: "square",
    side: 4
}));

Expected Output

12.566370614359172
16

If another shape type is added to the union without adding a matching case, assigning the remaining shape to never will produce a type-checking error.

12. Type Narrowing Techniques

Technique Purpose Example
typeof Checks a primitive runtime type category. typeof value === "string"
Truthiness Narrows according to truthy and falsy values. if (value)
Equality Checks a value against a specific value. status === "active"
in Checks whether a property exists. "course" in person
instanceof Checks an object's constructor or class relationship. value instanceof Date
Custom type guard Defines a reusable type predicate. value is string
Discriminated union Narrows object variants using a common literal property. result.status === "success"
never Helps verify exhaustive handling. const check: never = value

Summary

Type Narrowing helps TypeScript determine the specific type of a value using control flow and checks. Common techniques include typeof, truthiness, equality checks, the in operator, instanceof, custom type guards, discriminated unions and exhaustive checking with never.

Next, learn Conditional Types and how TypeScript selects a type based on a condition between types.