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:
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.