- Courses
- đź’»Programming Languages
- 🛡️TypeScript
- Narrowing, Guards & Control Flow Analysis
- Type Narrowing
On this page
TypeScript Type Narrowing: Complete Guide with Examples
Published on August 1, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Type narrowing is the process by which TypeScript refines a variable's type from a broad union type to a more specific one based on runtime checks. When you declare a variable with a union type — such as string | number — TypeScript cannot safely assume which type it is at any given point. Through control flow analysis, the compiler examines your conditional logic — if statements, switch cases, truthiness checks, and operators like typeof, instanceof, and in — and narrows the type within each branch. This allows you to access properties and methods that are only available on specific members of the union, all while maintaining full type safety. The most powerful application of narrowing is the discriminated union pattern, where a shared literal property (the discriminant) lets TypeScript distinguish between variants in a union of object types. Mastering narrowing is essential for writing robust, maintainable TypeScript code.
What Is Type Narrowing?​
Type narrowing is TypeScript's way of following your code's logic to understand what type a variable actually holds at a given moment. When you have a value that could be one of several types — a union type — the compiler restricts the set of possible types based on the checks you perform.
Consider a function that accepts a string | number:
function processValue(value: string | number) {
// Here, value is string | number — you cannot call toUpperCase()
// or toFixed() safely.
if (typeof value === "string") {
// Inside this block, TypeScript knows value is a string.
console.log(value.toUpperCase());
} else {
// Inside this block, TypeScript knows value is a number.
console.log(value.toFixed(2));
}
}
Within the if branch, TypeScript has narrowed value from string | number to just string. Within the else branch, it has narrowed it to number. This is type narrowing in action.
Narrowing with typeof​
The typeof operator is the most common and straightforward way to narrow primitive types. TypeScript understands typeof checks for the following values:
"string""number""boolean""bigint""symbol""undefined""object""function"
Basic Example​
function formatValue(value: string | number | boolean) {
if (typeof value === "string") {
return value.toUpperCase();
}
if (typeof value === "number") {
return value.toFixed(2);
}
// value is now narrowed to boolean
return value ? "Yes" : "No";
}
TypeScript refines the type step by step. After the first two checks, only boolean remains.
Handling null and undefined​
typeof null returns "object", which can be a source of confusion. Always check for null explicitly:
function processInput(input: string | null) {
if (typeof input === "string") {
// input is string
console.log(input.toUpperCase());
} else {
// input is null
console.log("No input provided");
}
}
Narrowing with instanceof​
Use instanceof when working with class instances or built-in objects like Date, Error, or RegExp. It checks whether an object was created by a specific constructor.
function formatDate(input: string | Date) {
if (input instanceof Date) {
// input is Date
return input.toISOString();
}
// input is string
return new Date(input).toISOString();
}
TypeScript recognizes instanceof checks as type guards and narrows the type accordingly.
Working with Custom Classes​
class Dog {
bark() { console.log("Woof!"); }
}
class Cat {
meow() { console.log("Meow!"); }
}
type Animal = Dog | Cat;
function makeSound(animal: Animal) {
if (animal instanceof Dog) {
animal.bark(); // animal is Dog
} else {
animal.meow(); // animal is Cat
}
}
Narrowing with the in Operator​
The in operator checks whether a property exists on an object. It is particularly useful for narrowing unions of object types that share some properties but differ in others.
type User = { name: string };
type Admin = { name: string; permissions: string[] };
function printInfo(person: User | Admin) {
if ("permissions" in person) {
// person is Admin
console.log(`Admin: ${person.name}, Permissions: ${person.permissions.join(", ")}`);
} else {
// person is User
console.log(`User: ${person.name}`);
}
}
TypeScript narrows the type based on the presence or absence of the property.
Truthiness Narrowing​
TypeScript also narrows types based on truthiness checks. This is useful for handling optional values or values that could be null or undefined.
function logValue(value: string | undefined) {
if (value) {
// value is string (truthy)
console.log(value.toUpperCase());
} else {
// value is undefined or empty string
console.log("No value provided");
}
}
Be cautious: truthiness checks also treat 0, "", false, null, undefined, and NaN as falsy. This can lead to unexpected narrowing in numeric contexts:
function processNumber(value: number | undefined) {
if (value) {
// value is number, but only if it's not 0
console.log(value.toFixed(2));
} else {
// value is either undefined OR 0
console.log("Value is zero or undefined");
}
}
Literal Types​
Literal types represent exact values, not just general types. They are the foundation of discriminated unions.
String Literals​
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction) {
// direction can only be one of the four strings
console.log(`Moving ${direction}`);
}
Number Literals​
type StatusCode = 200 | 400 | 404 | 500;
function handleStatus(code: StatusCode) {
switch (code) {
case 200: return "OK";
case 400: return "Bad Request";
case 404: return "Not Found";
case 500: return "Internal Server Error";
}
}
Boolean Literals​
type Flag = true | false;
Literal types work with const declarations because TypeScript infers the narrowest possible type.
const hello = "Hello World"; // Type is "Hello World", not string
let hi = "Hi World"; // Type is string
Discriminated Unions​
A discriminated union is a union of object types where each member shares a common property with a literal type. This common property — the discriminant — allows TypeScript to narrow the union precisely.
Basic Example​
type Circle = {
kind: "circle";
radius: number;
};
type Square = {
kind: "square";
size: number;
};
type Shape = Circle | Square;
function area(shape: Shape) {
switch (shape.kind) {
case "circle":
// shape is Circle
return Math.PI * shape.radius ** 2;
case "square":
// shape is Square
return shape.size ** 2;
}
}
The kind property is the discriminant. TypeScript uses it to narrow the type within each case block.
Why Discriminated Unions Are Powerful​
- Exhaustiveness checking: TypeScript can ensure all variants are handled.
- Type safety: Impossible states become impossible to represent.
- Autocompletion: Each branch gets full IntelliSense for the specific variant.
- Maintainability: Adding a new variant produces compile-time errors in all places that need to handle it.
Real-World Example: API Response​
type APIResponse =
| { status: "loading" }
| { status: "success"; data: string }
| { status: "error"; error: Error };
function handleResponse(response: APIResponse) {
if (response.status === "loading") {
console.log("Loading...");
} else if (response.status === "success") {
console.log(response.data.toUpperCase());
} else {
console.error(response.error.message);
}
}
TypeScript ensures that data only exists on "success" and error only exists on "error".
Putting It All Together​
Here is a realistic example combining multiple narrowing techniques:
type Result =
| { status: "success"; data: string }
| { status: "error"; error: Error }
| { status: "loading" };
function handleResult(result: Result) {
switch (result.status) {
case "success":
// result is { status: "success"; data: string }
console.log(result.data.toUpperCase());
break;
case "error":
// result is { status: "error"; error: Error }
console.error(result.error.message);
break;
case "loading":
// result is { status: "loading" }
console.log("Loading...");
break;
default:
// exhaustiveness check
const _exhaustive: never = result;
return _exhaustive;
}
}
Summary​
TechniqueUse CaseExampletypeofPrimitives (string, number, boolean, etc.)typeof value === "string"``instanceofClass instances (Date, Error, custom classes)value instanceof Date``inObject properties"property" in objectTruthinessnull, undefined, empty valuesif (value)Literal typesExact string, number, or boolean values`type Status = "active"Discriminated unionsObject unions with a shared literal propertyswitch (obj.kind)
Type narrowing is one of TypeScript's most powerful features. It allows you to write code that is both safe and expressive, leveraging runtime checks to inform the type system. By mastering typeof, instanceof, the in operator, literal types, and discriminated unions, you can build applications that are robust, maintainable, and a pleasure to work with.
Frequently Asked Questions​
What is type narrowing in TypeScript?
Type narrowing is the process by which TypeScript refines a variable's type from a broad union type to a more specific one based on runtime checks. When you use conditional logic like `if` statements, `switch` cases, or operators such as `typeof` or `instanceof`, TypeScript analyzes your code and restricts the possible types within each branch, allowing you to safely access members that are only available on specific types.
How does `typeof` help with type narrowing?
The `typeof` operator allows you to narrow primitive types. TypeScript understands `typeof` checks for `"string"`, `"number"`, `"boolean"`, `"bigint"`, `"symbol"`, `"undefined"`, `"object"`, and `"function"`. When you write `typeof value === "string"`, TypeScript narrows `value` to the `string` type within that branch. However, note that `typeof null` returns `"object"`, so always check for `null` explicitly.
What is the difference between `typeof` and `instanceof` for narrowing?
`typeof` is used for primitive types like strings, numbers, and booleans. `instanceof` is used for checking whether an object was created by a specific constructor or class, such as `Date`, `Error`, `RegExp`, or custom classes. `typeof` works with values, while `instanceof` works with objects and their prototype chain.
How does the `in` operator narrow types in TypeScript?
The `in` operator checks whether a property exists on an object. When used in a conditional, TypeScript narrows the object type to those union members that contain the property you checked. For example, `if ('permissions' in person)` narrows `person` to the type that has a `permissions` property, discarding types that don't.
What are literal types and why are they useful?
Literal types represent exact values rather than general types. For example, `"up"` is a literal type, while `string` is a general type. Literal types are useful because they allow you to create precise unions like `"up" | "down" | "left" | "right"`. They are the foundation of discriminated unions because they provide the discriminant values that TypeScript uses for narrowing.
What is a discriminated union and how does it work with narrowing?
A discriminated union is a union of object types where each member shares a common property with a literal type. This common property is called the discriminant. TypeScript uses the discriminant to narrow the union within a switch or if-else chain. For example, if your types all have a `kind` property with values like `"circle"` or `"square"`, checking `shape.kind` narrows the type to the corresponding variant in each branch.
Why does `-ErrorAction SilentlyContinue` not suppress some errors in PowerShell?
`-ErrorAction` only affects non-terminating errors. When a cmdlet internally calls `$PSCmdlet.ThrowTerminatingError()`, it generates a statement-terminating error that bypasses the `-ErrorAction` parameter entirely. To suppress terminating errors, you must set `$ErrorActionPreference = 'SilentlyContinue'` in the enclosing scope, because `$ErrorActionPreference` applies to both non-terminating and statement-terminating errors.
How do I know if a union type has been properly narrowed?
You can verify narrowing by checking for errors when accessing properties. If TypeScript allows you to access `value.toUpperCase()`, it means `value` has been narrowed to a string type. If it raises an error like `Property 'toUpperCase' does not exist on type 'number'`, the narrowing has not occurred correctly. You can also use the `never` type in an exhaustiveness check in the default case of a switch statement to ensure all union members are handled.
Can I create custom type guards for more complex narrowing?
Yes, TypeScript allows you to create custom type guards using functions that return a type predicate. The syntax is `function isString(value: unknown): value is string { return typeof value === 'string'; }`. When you call this function in a conditional, TypeScript will narrow the type based on the predicate.
Why does my discriminated union not narrow correctly with `if`/`else` statements?
If your `if`/`else` conditions are not correctly checking the discriminant, TypeScript cannot narrow the type. Ensure you are checking the shared literal property directly, like `if (result.status === "success")`. TypeScript only narrows when you check the discriminant property against a specific literal value.
What is exhaustive checking and why is it important with discriminated unions?
Exhaustive checking ensures that you have handled all possible variants in a discriminated union. By including a `default` case in a switch that assigns the remaining value to a variable of type `never`, TypeScript will raise an error if you have not handled all union members. This is important for maintainability because adding a new variant produces compile-time errors in all places that need to handle it.
Does TypeScript narrow types with truthiness checks like `if (value)`?
Yes, truthiness checks narrow types, but you should be careful. `if (value)` narrows `null`, `undefined`, `""`, `0`, `false`, and `NaN` to falsy, and everything else to truthy. This can lead to unexpected narrowing for numeric values because `0` is falsy, so within the `else` branch, the type is narrowed to `undefined | 0`, not just `undefined`. Consider explicit checks when dealing with numbers.
What is the relationship between type narrowing and control flow analysis?
Control flow analysis is the compiler feature that makes type narrowing possible. TypeScript tracks the types of variables as it analyzes the control flow of your program — through `if` statements, `switch` statements, loops, and function calls. When it encounters a type guard, it updates the tracked type for that variable within the corresponding branch. This allows TypeScript to know the precise type of a variable at any point in your code.
Can I use `in` to narrow types with optional properties?
Yes, `in` works with optional properties, but you need to be careful. If a property is optional in all members of a union, `in` may not narrow as expected. The `in` operator works best when you are narrowing between types where the property is present in some members and absent in others.
How do I handle narrowing with generic types?
Narrowing with generics is more limited because the generic type parameter is not fully known until the function is called. TypeScript cannot narrow the type parameter itself. However, you can use type guards that return the generic type with a constraint, or use `as` assertions judiciously.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Narrowing, Guards & Control Flow Analysis
Next
Custom Type Guards
-
What Is Type Narrowing?
-
Narrowing with
typeof- Basic Example
- Handling
nullandundefined
-
Narrowing with
instanceof- Working with Custom Classes
-
Narrowing with the
inOperator -
Truthiness Narrowing
-
Literal Types
- String Literals
- Number Literals
- Boolean Literals
-
Discriminated Unions
- Basic Example
- Why Discriminated Unions Are Powerful
- Real-World Example: API Response
-
Putting It All Together
-
Summary
-
Frequently Asked Questions
