TypeScript — Intersection Types
Utility types
interface User {
name: string;
age: number;
email: string;
}
type PartialUser = Partial<User>;
type RequiredUser = Required<User>;
type UserBasic = Pick<User, 'name' | 'email'>;
type UserWithoutEmail = Omit<User, 'email'>;
type UserMap = Record<string, User>;
Mapped types
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};
type Optional<T> = {
[K in keyof T]?: T[K];
};
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
Conditional types
type IsString<T> = T extends string ? true : false;
type A = IsString<'hello'>; // true
type B = IsString<42>; // false
Infer keyword
type ElementType<T> = T extends (infer U)[] ? U : T;
type X = ElementType<number[]>; // number
type Y = ElementType<string>; // string
Template literal types
type EventName = `on${Capitalize<'click' | 'hover'>}`;
// "onClick" | "onHover"
Mini Practice
Write TypeScript code that:
- Uses utility types (Partial, Pick, Omit)
- Creates a mapped type
- Uses conditional types
- Demonstrates template literal types
Up Next
In the next lesson, you'll learn about Decorators — class and method decorators.
Related Topics
Frequently Asked Questions about Intersection Types
What is Intersection Types in TypeScript?
Intersection Types is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Intersection Types?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Intersection Types.
Why is Intersection Types important in TypeScript?
Intersection Types is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.