ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Advanced TypeScript Utility Types Examples
// 1. Partial - Make all properties optional
interface User {
id: string;
name: string;
email: string;
}
type PartialUser = Partial<User>;
// Result: { id?: string; name?: string; email?: string }
// 2. Required - Make all properties required
type RequiredUser = Required<PartialUser>;
// Result: { id: string; name: string; email: string }
// 3. Pick - Select specific properties
type UserCredentials = Pick<User, 'email' | 'name'>;
// Result: { email: string; name: string }
// 4. Omit - Exclude specific properties
type UserWithoutId = Omit<User, 'id'>;
// Result: { name: string; email: string }
// 5. Custom Mapped Type - Make specific keys optional
type OptionalKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type UserWithOptionalEmail = OptionalKeys<User, 'email'>;
// Result: { id: string; name: string; email?: string }
// 6. Readonly - Make all properties readonly
type ReadonlyUser = Readonly<User>;
// Properties cannot be reassigned
// 7. Record - Create object type with specific keys and values
type UserRoles = Record<'admin' | 'user' | 'guest', string[]>;
// Result: { admin: string[]; user: string[]; guest: string[] }
// 8. Advanced: Recursive Readonly
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object
? DeepReadonly<T[P]>
: T[P];
};
interface NestedData {
user: User;
settings: { theme: string; notifications: boolean };
}
type ImmutableData = DeepReadonly<NestedData>;
// All nested properties are readonly!