Typescript Foundations / Utility Types

Extract

πŸ” Extract<T, U>

Extract<T, U> creates a new union type by keeping only the types that are also present in another type.

πŸ”Ή Example

type Role = "admin" | "user" | "guest";

type AllowedRole = Extract<Role, "admin" | "user">;

const role: AllowedRole = "admin"; // βœ…

Now AllowedRole becomes:

"admin" | "user"

So this is not allowed:

const role: AllowedRole = "guest"; // ❌ Error

πŸ’‘ Common Use

Extract is useful when you want to keep only specific members of an existing union type.

Remember: Extract<T, U> β†’ Keeps the types from T that match U.