TypeScript
Beginner
1 min read
Pick, Omit, Exclude, Extract, and NonNullable
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
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript