SyntaxStudy
Sign Up
TypeScript Pick, Omit, Exclude, Extract, and NonNullable
TypeScript Beginner 1 min read

Pick, Omit, Exclude, Extract, and NonNullable

Pick creates a new type containing only the keys K from T, while Omit creates a new type with all keys of T except K. These two utilities are complementary — use Pick when you want to whitelist a small number of properties, and Omit when you want to blacklist a small number. Both are heavily used when defining DTOs, view models, and API request/response types. Exclude and Extract operate on union types rather than object types. Exclude removes all members of T that are assignable to U, and Extract keeps only those members. They are the set difference and intersection operations for union types respectively. NonNullable is a specialisation of Exclude that removes null and undefined from a union. ReturnType extracts the return type of a function type T, and Parameters extracts the parameter types as a tuple. ConstructorParameters does the same for constructors. InstanceType gives the instance type of a constructor function. These function-related utility types are invaluable when you want to derive types from existing functions without duplicating type information.
Example
interface Employee {
    id: number;
    name: string;
    email: string;
    salary: number;
    department: string;
    startDate: Date;
}

// Pick — select only certain properties
type EmployeeCard  = Pick<Employee, "id" | "name" | "department">;
type PublicProfile = Pick<Employee, "name" | "email">;

// Omit — exclude certain properties
type EmployeeDTO    = Omit<Employee, "salary">;          // no salary
type NewEmployeeDTO = Omit<Employee, "id" | "startDate">; // no id/date yet

// Exclude and Extract on union types
type Primitive = string | number | boolean | null | undefined;
type Defined   = NonNullable<Primitive>; // string | number | boolean

type Status = "pending" | "active" | "inactive" | "banned";
type GoodStatus = Extract<Status, "pending" | "active">;  // "pending" | "active"
type BadStatus  = Exclude<Status, "pending" | "active">;  // "inactive" | "banned"

// ReturnType and Parameters
function createUser(name: string, email: string, age: number) {
    return { id: Math.random(), name, email, age, createdAt: new Date() };
}

type UserResult  = ReturnType<typeof createUser>;
// { id: number; name: string; email: string; age: number; createdAt: Date }

type CreateParams = Parameters<typeof createUser>;
// [name: string, email: string, age: number]

// InstanceType
class DatabaseConnection {
    constructor(public url: string) {}
    query(sql: string): unknown[] { return []; }
}

type DBInstance = InstanceType<typeof DatabaseConnection>;
// DatabaseConnection