Day 68 TypeScript Types — Advanced
TypeScript mein complex types define kar sakte hain — type aliases, union types, intersection types, literal types. Yeh types code ko self-documenting banate hain.
Type Aliases & Union
Custom types define karo.
// Type alias
type UserID = string | number;
type Status = "active" | "inactive" | "banned"; // literal union
type User = {
id: UserID;
name: string;
email: string;
status: Status;
age?: number; // optional
readonly createdAt: Date; // cannot change
};
// Intersection type
type Admin = User & {
role: "admin";
permissions: string[];
};
// Usage
const user: User = {
id: "usr-123",
name: "Zohaib",
email: "z@test.com",
status: "active",
createdAt: new Date()
};
// Type guard
function isAdmin(user: User | Admin): user is Admin {
return (user as Admin).role === "admin";
}
if (isAdmin(user)) {
console.log(user.permissions); // TS knows it's Admin here
}
Utility Types
TypeScript built-in utility types.
type User = { name: string; email: string; age: number; };
// Partial — sab optional
type UpdateUser = Partial<User>; // { name?: string; email?: string; age?: number; }
// Required — sab required
type FullUser = Required<User>;
// Pick — subset
type LoginData = Pick<User, "email">; // { email: string }
// Omit — exclude
type PublicUser = Omit<User, "email">; // { name, age }
// Record
type Scores = Record<string, number>;
const scores: Scores = { math: 90, english: 85 };
// Readonly
type ImmutableUser = Readonly<User>;
// const u: ImmutableUser = { name: "Ali", email: "a@b.com", age: 25 };
// u.name = "Ahmed"; // ❌ Error!
🎯 Practice Challenge
Product type banao. ProductWithoutId, PartialProduct, ReadonlyProduct utility types banao. Function likhao jo sab accept kare.