Utility Types (Part 2)
Advanced utility types for extracting/removing fields and inferring function types (Pick, Omit, Extract, Exclude, ReturnType).
🧑🏫 Sabse pehle — simple mein samjho#
Pichhle notes mein humne object ko completely modify (sab optional, sab readonly) kiya. Lekin agar tumhe sirf ek ya do properties nikalni hon ya hatani hon? Ya phir function ki return type ka pata lagana ho? Ye Part 2 un advanced manipulations ke baare mein hai.
1. Pick<Type, Keys> (Extract Selected Properties)#
Constructs a type by picking a specific set of properties (Keys) from a larger type.
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
}
// The User object is large, but the frontend only needs to display the id and name
type PublicUser = Pick<User, "id" | "name">;
/* Evaluates to:
{
id: number;
name: string;
}
*/
const pUser: PublicUser = { id: 1, name: "Tarun" };
2. Omit<Type, Keys> (Remove Selected Properties)#
This is the opposite of Pick. It's useful when you want to keep almost everything from a large list, but remove just 1 or 2 specific properties.
// Remove the PasswordHash, but keep everything else
type SafeUser = Omit<User, "passwordHash">;
const sUser: SafeUser = { id: 1, name: "Tarun", email: "t@t.com" };
3. Exclude<UnionType, ExcludedMembers> (Union Filter - Remove)#
While Pick/Omit operate on object properties, Exclude and Extract operate strictly on Union types (e.g., A | B | C).
Exclude constructs a type by removing from the union all types that you don't want.
type Status = "success" | "error" | "pending";
// Remove the 'error' status
type NonErrorStatus = Exclude<Status, "error">; // "success" | "pending"
4. Extract<Type, Union> (Union Filter - Keep)#
Constructs a type by extracting from the union only those types that match the specified criteria.
type MixedTypes = string | number | boolean | string[];
// Extract only strings or string-related types
type OnlyStrings = Extract<MixedTypes, string | string[]>; // string | string[]
5. ReturnType<Type> (What Does the Function Return?)#
Sometimes we utilize functions from third-party libraries that didn't explicitly export their return types. You can use TS to extract (steal) the return type straight from the function signature.
function calculateHeavyMaths() {
return { val1: 10, val2: "Hello" };
}
// Extracted the return type of typeof calculateHeavyMaths!
type MathResult = ReturnType<typeof calculateHeavyMaths>;
/*
type MathResult = {
val1: number;
val2: string;
}
*/
6. Parameters<Type> (What Parameters Does the Function Take?)#
Constructs a tuple type (an Array of types) out of the types used in the parameters of a given function.
function greetUser(name: string, age: number) {}
type GreetParams = Parameters<typeof greetUser>; // [name: string, age: number]