Chapter 8TypeScript~1 min read
Enums आणि Utility Types
TypeScript चे Powerful Built-ins
TypeScript मध्ये काही built-in utility types आहेत जे existing types manipulate करतात — Partial, Required, Pick, Omit, Record. हे production code मध्ये खूप useful आहेत.
Enum — named constants
typescript
// Numeric enum
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
// String enum (better for debugging)
enum UserRole {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST",
}
function handleRole(role: UserRole): void {
if (role === UserRole.Admin) {
console.log("Full access!");
}
}
handleRole(UserRole.Admin);
handleRole("ADMIN"); // ❌ ERRORUtility Types
typescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
// Partial<T> — सगळ्या properties optional करतो
type PartialUser = Partial<User>;
// { id?: number; name?: string; email?: string; password?: string }
// Required<T> — सगळ्या properties required करतो
type RequiredUser = Required<PartialUser>;
// Pick<T, Keys> — फक्त select properties घ्या
type PublicUser = Pick<User, "id" | "name" | "email">;
// Omit<T, Keys> — select properties वगळा
type UserWithoutPassword = Omit<User, "password">;
// Record<Keys, Type> — object type बनवा
type RolePermissions = Record<UserRole, string[]>;💡
API response बनवताना Omit<User, "password"> — हे pattern खूप common आहे. Password कधीही frontend ला पाठवू नका!
✅ Key Points — लक्षात ठेवा
- ▸Enum — named constants group
- ▸String enums — debugging मध्ये helpful
- ▸Partial<T> — सगळं optional
- ▸Pick<T, K> — select properties
- ▸Omit<T, K> — properties हटवा
0/9 chapters पूर्ण