Utility Types (Part 1)
Built-in generic helpers to transform existing types (Partial, Required, Readonly, Record).
🧑🏫 Sabse pehle — simple mein samjho#
Socho tumne ek bada sa User interface banaya. Phir tum ek API bana rahe ho jisme "Update Profile" ka feature hai. Update API mein toh user sirf ek ya do cheez bhejega (jaise sirf naam, ya sirf email). Tum kya uske liye ek naya "UpdateUser" type banaoge jisme sab optional hoga? Nahi! TypeScript tumhe kuch readymade "Utility Types" (tools) deta hai jo purane types ko modify/transform karke naye types banate hain.
1. Partial<Type> (Make Everything Optional)#
This utility constructs a type with all properties of the original type set to optional (?). It is absolutely perfect for profile updates (PATCH requests).
interface User {
id: number;
name: string;
email: string;
}
// When creating a User object, all three fields are mandatory
const newUser: User = { id: 1, name: "Tarun", email: "t@t.com" };
// When updating, the user might only provide the email
function updateUser(id: number, updates: Partial<User>) {
// Here, the 'updates' parameter's type evaluates to:
// { id?: number, name?: string, email?: string }
}
updateUser(1, { email: "new@t.com" }); // ✅
2. Required<Type> (Make Everything Mandatory)#
This is the exact opposite of Partial. If a type originally had optional fields (marked with ?), this utility constructs a new type where all those fields are stripped of their optional status and made strictly required.
interface Props {
width?: number;
height?: number;
}
// If I want to guarantee that my internal function receives all dimensions:
const myProps: Required<Props> = { width: 100, height: 200 };
// Missing even a single property will now result in an error
3. Readonly<Type> (Do Not Touch)#
If you want to ensure that a specific object is never mutated (updated) after its initial creation (such as Redux State), use this. It applies the readonly modifier to every field.
interface Config {
apiKey: string;
url: string;
}
const appConfig: Readonly<Config> = {
apiKey: "12345",
url: "https://api.test.com"
};
// appConfig.apiKey = "999"; // ❌ ERROR: Cannot assign to 'apiKey' because it is a read-only property
4. Record<Keys, Type> (Creating Dictionaries/Maps)#
If you need to construct an object (dictionary) where the types of the keys and the values are strictly predefined. For instance, an object where all properties are strings and all values are numbers.
// An object containing 'string' type keys and 'number' type values
const userAges: Record<string, number> = {
Tarun: 25,
Rahul: 28,
Amit: "twenty" // ❌ ERROR: Type 'string' is not assignable to type 'number'
};
// Record becomes extremely powerful when combined with Literal Types
type Roles = "admin" | "editor" | "viewer";
const permissions: Record<Roles, boolean> = {
admin: true,
editor: true,
viewer: false
};
// If you forget even one key from the Roles type, TS will throw a warning!