Middle
TypeScript: what are Omit and Pick? What is the difference between union and intersection types? What will happen if an intersection type is passed to Omit?
sobes.tech AI
Answer from AI
In TypeScript:
- Pick<T, K> creates a new type by selecting only the properties with keys K from type T.
- Omit<T, K> creates a new type by excluding properties with keys K from type T.
Example:
interface User {
id: number;
name: string;
age: number;
}
type UserName = Pick<User, 'name'>; // { name: string }
type UserWithoutAge = Omit<User, 'age'>; // { id: number; name: string; }
Difference between union and intersection types:
- Union (|) — the value can be one of several types. For example,
string | number— either a string or a number. - Intersection (&) — the value must satisfy all types simultaneously. For example,
A & B— an object that has properties of both A and B.
If an intersection type is passed to Omit, Omit will be applied to the entire intersection, meaning properties will be excluded from each type in the intersection. However, this can lead to unexpected results, as the intersection requires all properties to be present, and Omit removes them, which may make the type incompatible.
Example:
type A = { a: number; b: string; };
type B = { b: string; c: boolean; };
type AB = A & B; // { a: number; b: string; c: boolean; }
type Result = Omit<AB, 'b'>; // { a: number; c: boolean; }
Here, the property 'b' will be removed from the result, so Result is a type with 'a' and 'c'.