नमस्ते दोस्तों! 🙏
स्वागत है The Easy Master पर!
क्या तुमने कभी TypeScript में ऐसे code देखे हैं:
type PartialUser = Partial<User>;
type UserName = Pick<User, "name">;
type UserWithoutAge = Omit<User, "age">;और सोचा है – “ये क्या जादू है? Partial, Pick, Omit – ये built-in होते हैं?”
हाँ दोस्तों! ये हैं TypeScript Utility Types – जो तुम्हारी बहुत सारी मेहनत बचा सकते हैं।
आज हम TypeScript Utility Types in Hindi में सबसे ज्यादा use होने वाले utility types को detailed examples के साथ समझेंगे:
- Partial – सब properties optional बनाओ
- Pick – कुछ specific properties चुनो
- Omit – कुछ properties हटाओ
- Readonly – properties को immutable बनाओ
- Record – key-value pair का type define करो
- Exclude / Extract – union types में से कुछ हटाओ या चुनो
- NonNullable – null/undefined हटाओ
तो चलिए शुरू करते हैं – Utility Types का मास्टर बनने का सफर! 🚀
Table of Contents
1. Utility Types क्या होते हैं?
Utility Types TypeScript के built-in generic types हैं – जो common type transformations को आसान बनाते हैं।
तुम बिना utility types के भी काम कर सकते हो, लेकिन उसके लिए तुम्हें बहुत सारा repetitive code लिखना पड़ेगा। Utility types तुम्हारा code short, clean और type-safe बनाते हैं।
Example – बिना utility type के:
interface User {
id: number;
name: string;
email: string;
age: number;
}
// सारी properties optional चाहिए? – खुद लिखो
type PartialUserManual = {
id?: number;
name?: string;
email?: string;
age?: number;
};Utility type Partial के साथ:
type PartialUser = Partial<User>; // एक line में काम हो गया!अब देखते हैं हर utility type को detail में।
2. Partial<Type> – सब कुछ optional
Syntax: Partial<Type>
काम: किसी existing type की सभी properties को optional बना देता है (? लगा देता है)।
Real use case: Update operation में – जहाँ user की सिर्फ कुछ fields update होती हैं, सब नहीं।
interface User {
id: number;
name: string;
email: string;
age: number;
}
function updateUser(id: number, updates: Partial<User>): User {
// updates में id, name, email, age में से कोई भी property हो सकती है, या सब
console.log(`Updating user ${id} with`, updates);
return { id, ...updates } as User;
}
// Valid calls:
updateUser(1, { name: "Rahul" }); // ✅ sirf name
updateUser(2, { email: "new@mail.com", age: 25 }); // ✅ email + age
updateUser(3, {}); // ✅ empty object bhi allowedBehind the scenes – Partial कैसे काम करता है?
// TypeScript का internal implementation (simplified)
type MyPartial<T> = {
[P in keyof T]?: T[P];
};यानी T की हर property के सामने ? लगा दो।
Common mistake: Partial का use तब मत करो जब तुम्हें सभी properties चाहिए ही चाहिए – तब original type use करो।
3. Pick<Type, Keys> – चुनिंदा properties
Syntax: Pick<Type, Keys>
काम: किसी existing type में से कुछ specific properties चुनकर नया type बनाता है।
Real use case: API response में से सिर्फ जरूरी fields लेना।
interface Product {
id: number;
name: string;
price: number;
description: string;
stock: number;
createdAt: Date;
}
// सिर्फ product card दिखाने के लिए चाहिए: id, name, price
type ProductCard = Pick<Product, "id" | "name" | "price">;
const card: ProductCard = {
id: 101,
name: "Laptop",
price: 55000
// description, stock, createdAt – allowed nahi hai
};Multiple keys kaise likhein? – Union type की तरह: "id" | "name" | "price"
Behind the scenes:
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};यहाँ K extends keyof T guarantee करता है कि तुम सिर्फ वही keys pick kar sakte ho जो T में मौजूद हैं।
Common mistake: ऐसी key pick करना जो type में exist नहीं करती:
type Wrong = Pick<Product, "category">; // ❌ Error: 'category' does not exist4. Omit<Type, Keys> – unwanted properties हटाओ
Syntax: Omit<Type, Keys>
काम: किसी existing type में से कुछ properties हटाकर नया type बनाता है। Pick का उल्टा।
Real use case: Password, credit card number जैसी sensitive fields को API response से हटाना।
interface User {
id: number;
name: string;
email: string;
password: string;
creditCardNumber: string;
}
// Public profile में password aur creditCardNumber नहीं दिखाना
type PublicUser = Omit<User, "password" | "creditCardNumber">;
const publicProfile: PublicUser = {
id: 1,
name: "Priya",
email: "priya@example.com"
// password और creditCardNumber – allowed nahi
};Omit vs Pick – कब क्या use करें?
| अगर तुम चाहते हो… | तो use करो… |
|---|---|
| सिर्फ 2-3 properties चुननी हैं | Pick (कम लिखना पड़ता है) |
| सिर्फ 2-3 properties हटानी हैं | Omit (बाकी सब रखना है) |
Behind the scenes: Omit, Pick और Exclude के combination से बना है:
type MyOmit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;लेकिन तुम्हें ये detail जानने की जरूरत नहीं – बस use करना आना चाहिए।
5. Readonly<Type> – एक बार सेट, फिर बदलो मत (H2)
Syntax: Readonly<Type>
काम: सभी properties को readonly बना देता है – यानी value assign करने के बाद बदल नहीं सकते।
Real use case: Configuration objects, constants, या ऐसे data जो runtime में change नहीं होने चाहिए।
interface Config {
apiUrl: string;
timeout: number;
retries: number;
}
const config: Readonly<Config> = {
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3
};
// config.apiUrl = "https://new.com"; // ❌ Error: Cannot assign to 'apiUrl' because it is a read-only propertyArray के लिए भी use कर सकते हो:
const numbers: Readonly<number[]> = [1, 2, 3];
// numbers.push(4); // ❌ Error
// numbers[0] = 10; // ❌ ErrorShorthand: TypeScript में readonly keyword properties पर भी लगा सकते हो, लेकिन Readonly<T> पूरे type पर लगाता है।
6. Record<Keys, Type> – dictionary या map बनाओ
Syntax: Record<Keys, Type>
काम: एक object type बनाता है जिसकी keys Keys type की होंगी और values Type type की होंगी।
Real use case: Map / Dictionary जहाँ key-value pairs का type fix हो।
// Key string होगी, value number होगी
type ScoreMap = Record<string, number>;
const scores: ScoreMap = {
"Rahul": 85,
"Priya": 92,
"Amit": 78
};
// Key specific union type की भी हो सकती है
type UserRole = "admin" | "user" | "guest";
type RolePermissions = Record<UserRole, string[]>;
const permissions: RolePermissions = {
admin: ["read", "write", "delete"],
user: ["read", "write"],
guest: ["read"]
// Agar koi key missing hogi to error
};Important: Record की सभी keys mandatory होती हैं। Agar koi key missing hai to error aayega।
Behind the scenes:
type MyRecord<K extends keyof any, T> = {
[P in K]: T;
};7. Exclude<UnionType, ExcludedMembers>
Syntax: Exclude<UnionType, ExcludedMembers>
काम: Union type में से कुछ members को हटा देता है।
Real use case: Kisi union type से specific values को बाहर करना।
type Status = "loading" | "success" | "error" | "idle";
// "error" और "idle" हटाओ
type LoadingOrSuccess = Exclude<Status, "error" | "idle">;
// Result: "loading" | "success"
type WithoutError = Exclude<Status, "error">;
// Result: "loading" | "success" | "idle"String literal types ke saath bahut useful hai.
8. Extract<UnionType, ExtractedMembers>
Syntax: Extract<UnionType, ExtractedMembers>
काम: Union type में से सिर्फ specific members निकालता है। Exclude का उल्टा।
type Status = "loading" | "success" | "error" | "idle";
type ErrorOrIdle = Extract<Status, "error" | "idle">;
// Result: "error" | "idle"
type SuccessOnly = Extract<Status, "success">;
// Result: "success"Real use case: जब तुम union में से कुछ specific types ही चाहते हो।
9. NonNullable<Type>
Syntax: NonNullable<Type>
काम: Type से null और undefined हटा देता है।
type MaybeString = string | null | undefined;
type DefinitelyString = NonNullable<MaybeString>; // string
type Mixed = number | null | boolean | undefined;
type NoNull = NonNullable<Mixed>; // number | booleanReal use case: Array filter के बाद typescript को null/undefined नहीं रहने का भरोसा दिलाना।
const arr = [1, 2, null, 3, undefined, 4];
const filtered = arr.filter((item): item is NonNullable<typeof item> => item !== null && item !== undefined);
// filtered type: number[]10. ReturnType<Type>
Syntax: ReturnType<Type>
काम: किसी function type के return type को extract करता है।
function fetchUser() {
return { id: 1, name: "Rahul" };
}
type FetchUserReturn = ReturnType<typeof fetchUser>;
// Result: { id: number; name: string; }
// Arrow function ke saath
const getProduct = () => ({ id: 101, price: 500 });
type ProductType = ReturnType<typeof getProduct>;
// { id: number; price: number; }Important: ReturnType function type पर काम करता है, function value पर नहीं। इसलिए typeof use karna padta hai.
11. Real-world Project Examples
Example 1: Form handling with Partial
interface FormData {
username: string;
email: string;
password: string;
confirmPassword: string;
}
class FormManager {
private data: Partial<FormData> = {};
updateField<K extends keyof FormData>(field: K, value: FormData[K]) {
this.data[field] = value;
}
submit() {
// Check if all required fields are present
const required: (keyof FormData)[] = ["username", "email", "password"];
const isValid = required.every(field => this.data[field] !== undefined);
if (!isValid) throw new Error("Missing fields");
// Submit logic
}
}Example 2: API Response with Pick/Omit
interface ApiUser {
id: number;
name: string;
email: string;
password_hash: string;
created_at: Date;
updated_at: Date;
}
// Client को भेजने के लिए sensitive fields hatao
type PublicUser = Omit<ApiUser, "password_hash">;
// Dashboard list के लिए sirf id, name chahiye
type UserListItem = Pick<ApiUser, "id" | "name">;
function getPublicUser(user: ApiUser): PublicUser {
const { password_hash, ...rest } = user;
return rest;
}Example 3: Configuration with Readonly and Record
type Environment = "development" | "staging" | "production";
interface EnvConfig {
apiUrl: string;
logLevel: "debug" | "info" | "error";
maxRetries: number;
}
const configs: Record<Environment, Readonly<EnvConfig>> = {
development: {
apiUrl: "http://localhost:3000",
logLevel: "debug",
maxRetries: 1
},
staging: {
apiUrl: "https://staging.api.com",
logLevel: "info",
maxRetries: 3
},
production: {
apiUrl: "https://api.com",
logLevel: "error",
maxRetries: 5
}
};
// configs.development.apiUrl = "new"; // ❌ Readonly se protected12. Common Mistakes + Solutions
Mistake 1: Pick/Omit में गलत key देना
interface User { id: number; name: string; }
type Wrong = Pick<User, "id" | "age">; // ❌ 'age' does not existSolution: हमेशा keyof T check करो या IDE की autocomplete use करो।
Mistake 2: Partial को Required की तरह use करना
function saveUser(user: Partial<User>) {
console.log(user.id); // ⚠️ user.id possibly undefined
}Solution: Required fields को check करो या Required<Partial<T>> use करो (खुद बनाना पड़ेगा)।
Mistake 3: Record में missing keys
type Colors = "red" | "green" | "blue";
type ColorCodes = Record<Colors, string>;
const codes: ColorCodes = { red: "#ff0000", green: "#00ff00" }; // ❌ blue missingSolution: सभी keys provide करो, या Partial<Record<Colors, string>> use करो।
Mistake 4: ReturnType को function value पर use karna
function foo() { return 42; }
type T = ReturnType<foo>; // ❌ 'foo' refers to a value, but is being used as a typeSolution: typeof use करो: ReturnType<typeof foo>
13. Quick Cheat Sheet (Table)
| Utility Type | क्या करता है? | Example |
|---|---|---|
Partial<T> | सब properties optional | Partial<{a: string}> → {a?: string} |
Pick<T, K> | सिर्फ K keys चुनो | Pick<User, "id" | "name"> |
Omit<T, K> | K keys हटाओ | Omit<User, "password"> |
Readonly<T> | सब properties readonly | Readonly<Config> |
Record<K, T> | Key K, value T वाला object | Record<string, number> |
Exclude<U, X> | U में से X हटाओ | Exclude<"a"|"b", "a"> → "b" |
Extract<U, X> | U में से सिर्फ X लो | Extract<"a"|"b", "a"> → "a" |
NonNullable<T> | null/undefined हटाओ | NonNullable<string|null> → string |
ReturnType<F> | Function ka return type | ReturnType<()=>number> → number |
14. FAQ
Q1: Utility types ko custom types ke saath combine kar sakte hain?
हाँ, type AdminUser = Readonly<Pick<User, "id" | "role">> & { permissions: string[] };
Q2: Kya main khud apna utility type bana sakta hoon?
बिल्कुल! Mapped types और conditional types से खुद के utility types बना सकते हो।
Q3: Partial और ? manually lagane mein kya fark hai?
Partial automatically sab properties pe lagta hai. Manual se code lengthy ho jata hai, especially agar type mein 10+ properties hain.
Q4: Omit और Exclude में क्या अंतर है?
Omit objects ke liye hai (properties hatao), Exclude union types ke liye (members hatao).
Q5: Kya Pick multiple nested properties le sakta hai?
Nahi, Pick sirf top-level properties ke liye hai. Nested ke liye तुम्हें खुद type banana padega.
Q6: Record में keys dynamic ho sakti hain?
Ha, Record<string, T> se koi bhi string key allowed hai.
Q7: ReturnType async function ke saath kaam karega?
Haan, Promise<Type> return karega. Agar actual resolved type chahiye to Awaited<ReturnType<F>> use करो।
Q8: Utility types performance affect karte hain?
Nahi, ye sirly compile-time types hain. Runtime performance par zero effect.
Q9: Kya main utility types ko class implements mein use kar sakta hoon?
Haan, class MyClass implements Partial<User> allowed hai, lekin optional properties ko implement karte waqt careful rehna.
Q10: TypeScript 5.x mein koi naya utility type aaya hai?
TypeScript 5.0 mein NoInfer<T> aaya, aur 5.4 mein improved narrowing. Awaited<T> bhi useful hai for Promises.
15. Conclusion + Call to Action
बहुत बढ़िया दोस्तों! आज हमने TypeScript Utility Types in Hindi को बिल्कुल detail में समझा।
Quick recap:
- Partial – update operations के लिए lifesaver
- Pick / Omit – API responses को clean रखने के लिए
- Readonly – config, constants के लिए safety
- Record – dictionary / map types के लिए
- Exclude / Extract – union types पर precision control
- ReturnType – function return types extract करने के लिए
मेरा personal experience: जब मैंने पहली बार utility types use kiye, तो मेरा code 40% short ho gaya. पहले मैं हर type को manually define karta tha – अब Pick और Omit से 1 line mein kaam हो जाता है।
अब तुम्हारी बारी है!
नीचे comment में बताओ:
- तुम्हें कौन सा utility type सबसे ज्यादा useful लगा?
- क्या तुमने कभी
Recordका use dictionary की तरह किया है? - अगला topic क्या चाहिए? (Conditional Types? Mapped Types? Template Literal Types?)
The Easy Master पर बने रहो। Happy Coding! 💻🚀
Resources
- TypeScript Utility Types Documentation
- TypeScript Playground – Try Utility Types
- TypeScript Deep Dive – Utility Types
Additional Resources
- Master ES6: A Complete Feature Guide with Examples
- Top 10 React Libraries and Tools Every Developer Must Know in 2025
- Top 10 Free APIs for Practice in 2026
- JavaScript Deep Dive 2026: Closures, Promises & Event Loop
- TypeScript Mastery in Hindi | Web Development 2026 Guide
- TypeScript Interfaces vs Type Alias in Hindi – Advanced Examples के साथ 2026
- TypeScript Generics in Hindi – बिना डर के लिखो Flexible Code