You are viewing a free preview of this lesson.
Subscribe to unlock all 12 lessons in this course and every other course on LearningBro.
Union and intersection types are two of TypeScript's most powerful features for composing types. Combined with type guards, they allow you to write code that is both flexible and safe. This lesson covers how to create, narrow, and combine types effectively.
A union type describes a value that can be one of several types. Use the pipe | operator:
type StringOrNumber = string | number;
function formatValue(value: StringOrNumber): string {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value.toFixed(2);
}
formatValue('hello'); // 'HELLO'
formatValue(3.14159); // '3.14'
Union types are not limited to two members:
type Status = 'idle' | 'loading' | 'success' | 'error';
type PrimitiveValue = string | number | boolean | null;
When you have a union type, you must narrow it before accessing type-specific properties. TypeScript recognises several built-in type guards.
The typeof operator works for primitive types:
function processInput(input: string | number | boolean): string {
if (typeof input === 'string') {
return input.trim(); // input is string here
} else if (typeof input === 'number') {
return input.toString(); // input is number here
} else {
return input ? 'yes' : 'no'; // input is boolean here
}
}
Use instanceof for class instances:
class Dog {
bark() { return 'Woof!'; }
}
class Cat {
meow() { return 'Meow!'; }
}
function makeSound(animal: Dog | Cat): string {
if (animal instanceof Dog) {
return animal.bark(); // animal is Dog
}
return animal.meow(); // animal is Cat
}
The in operator checks whether a property exists on an object:
interface Fish {
swim: () => void;
}
interface Bird {
fly: () => void;
}
function move(animal: Fish | Bird): void {
if ('swim' in animal) {
animal.swim(); // animal is Fish
} else {
animal.fly(); // animal is Bird
}
}
You can write your own type guard functions using the is keyword:
interface ApiError {
code: number;
message: string;
}
interface ApiSuccess {
data: unknown;
}
function isApiError(response: ApiError | ApiSuccess): response is ApiError {
return 'code' in response && 'message' in response;
}
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.