Safely Working with Multiple Types - Textnotes

Safely Working with Multiple Types


Learn how type narrowing works in TypeScript to safely handle union types. This module explains using typeof checks, the in operator, and instanceof checks with real-world examples.

1. Using typeof

The typeof operator is used to narrow primitive types such as string, number, and boolean at runtime.

Basic Example


function processValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}

TypeScript understands the type inside each conditional block and allows only valid operations.

Common Use Case


function printLength(input: string | number): number {
if (typeof input === "string") {
return input.length;
}
return input.toString().length;
}

The typeof operator is commonly used when handling input from forms or APIs.

2. Using the in Operator

The in operator is used to check if a property exists on an object. It helps narrow types when working with object unions.

Basic Example


type Admin = {
name: string;
privileges: string[];
};

type User = {
name: string;
};

function printUserInfo(person: Admin | User): void {
if ("privileges" in person) {
console.log(person.privileges);
} else {
console.log(person.name);
}
}

The presence of the property narrows the type automatically.

Real-World Example


type Car = {
drive: () => void;
};

type Boat = {
sail: () => void;
};

function moveVehicle(vehicle: Car | Boat): void {
if ("drive" in vehicle) {
vehicle.drive();
} else {
vehicle.sail();
}
}

3. Instanceof Checks

The instanceof operator is used to check whether an object is an instance of a specific class.

Basic Example


class Dog {
bark() {
console.log("Barking");
}
}

class Cat {
meow() {
console.log("Meowing");
}
}

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

Real-World Example


class ApiError extends Error {
code: number;

constructor(message: string, code: number) {
super(message);
this.code = code;
}
}

function handleError(error: Error | ApiError): void {
if (error instanceof ApiError) {
console.log(error.code);
} else {
console.log(error.message);
}
}

Conclusion

Type narrowing is a powerful feature in TypeScript that ensures safe access to properties and methods when working with union types. Using typeof, the in operator, and instanceof checks helps write reliable, maintainable, and error-free code in real-world applications.