TypeScript
Utility Types
TypeScript ships with generic types that transform other types. They save you from writing the same shape twice.
All examples use this type:
interface User {
id: number;
name: string;
email?: string;
}
Changing Properties
| Utility | Result |
|---|---|
Partial<T> | Every property becomes optional. |
Required<T> | Every property becomes required. |
Readonly<T> | Every property becomes readonly. |
// Useful for updates: send only the fields that change
function updateUser(id: number, changes: Partial<User>) {
// ...
}
updateUser(1, { name: "Pirate Dev" }); // OK: id and email can be left out
Picking Properties
| Utility | Result |
|---|---|
Pick<T, K> | Only the properties K. |
Omit<T, K> | Every property except K. |
type UserPreview = Pick<User, "id" | "name">; // { id: number; name: string }
type NewUser = Omit<User, "id">; // { name: string; email?: string }
Building Object Types
Record<K, V> is an object whose keys are K and whose values are V:
type Role = "admin" | "editor" | "viewer";
const permissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
viewer: ["read"],
};
With a union of literal keys, TypeScript also checks that every key is present.
Filtering Unions
| Utility | Result |
|---|---|
Exclude<U, X> | Members of U that are not assignable to X. |
Extract<U, X> | Members of U that are assignable to X. |
NonNullable<T> | T without null and undefined. |
type Status = "active" | "inactive" | "banned";
type Allowed = Exclude<Status, "banned">; // "active" | "inactive"
type Name = NonNullable<string | null | undefined>; // string
Working with Functions
| Utility | Result |
|---|---|
ReturnType<F> | The type a function returns. |
Parameters<F> | The function's parameter types, as a tuple. |
Awaited<T> | The value inside a Promise (unwrapped). |
function createUser(name: string, admin: boolean) {
return { id: Date.now(), name, admin };
}
type Created = ReturnType<typeof createUser>; // { id: number; name: string; admin: boolean }
type Args = Parameters<typeof createUser>; // [name: string, admin: boolean]
type Data = Awaited<Promise<string[]>>; // string[]
typeof createUser turns a value (the function) into its type, so a utility can read it.
