U

Utility Types

TypeScript provides built-in utility types for common type transformations.

Code

typescript
1interface User {
2 id: number;
3 name: string;
4 email: string;
5 password: string;
6 createdAt: Date;
7}
8
9// Partial<T> - makes all properties optional
10type PartialUser = Partial<User>;
11const updateData: PartialUser = { name: "New Name" };
12
13// Required<T> - makes all properties required
14interface Config {
15 host?: string;
16 port?: number;
17}
18type RequiredConfig = Required<Config>;
19
20// Pick<T, K> - select specific properties
21type UserCredentials = Pick<User, "email" | "password">;
22const creds: UserCredentials = { email: "a@b.com", password: "secret" };
23
24// Omit<T, K> - exclude specific properties
25type PublicUser = Omit<User, "password">;
26const publicUser: PublicUser = {
27 id: 1,
28 name: "Alice",
29 email: "alice@example.com",
30 createdAt: new Date(),
31};
32
33// Readonly<T> - make all properties readonly
34type ImmutableUser = Readonly<User>;
35
36// Record<K, V> - create object type with specific keys
37type UserRoles = Record<string, "admin" | "user" | "guest">;
38const roles: UserRoles = {
39 alice: "admin",
40 bob: "user",
41 guest1: "guest",
42};
43
44// Extract<T, U> - extract types assignable to U
45type AllTypes = string | number | boolean | null;
46type OnlyStrings = Extract<AllTypes, string | number>; // string | number
47
48// Exclude<T, U> - exclude types assignable to U
49type NonNullTypes = Exclude<AllTypes, null>; // string | number | boolean
50
51// ReturnType<T> - get function return type
52function createUser(name: string) {
53 return { id: Math.random(), name, createdAt: new Date() };
54}
55type CreatedUser = ReturnType<typeof createUser>;
56
57// Parameters<T> - get function parameter types
58type CreateUserParams = Parameters<typeof createUser>; // [string]
59
60console.log("Partial user update:", updateData);
61console.log("Public user:", publicUser);

Run this example locally

$ npx ts-node types/utility-types.ts