← العودة إلى الدورة: TypeScript from scratch

Utility types: Partial, Pick, Omit, Record

الفيديو قريبًا

As a project grows, a problem appears: you need variants of a type that already exists. A full user for reading, a partial one for updating, one without the password for display. Copying and pasting the interface with small changes creates duplication and drift. TypeScript ships a collection of utility types, ready-made generic types that transform other types. They are the same generics you studied last week, written by the language team and ready to use.

Partial, Required and Readonly

Partial<T> turns all properties of T into optional ones: it is perfect for update functions, where the caller sends only the fields that change. Required<T> does the opposite, making all properties mandatory. Readonly<T> marks all of them read-only, ideal for returning data that must not be modified. All three apply only to the first level of properties; nested objects are not affected.

typescript
interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

function updateUser(user: User, changes: Partial<Omit<User, 'id'>>): User {
  return { ...user, ...changes };
}

const ana: User = { id: 1, name: 'Ana', email: 'ana@example.com', password: 'secret' };
const updated = updateUser(ana, { name: 'Ana Maria' }); // only name sent
console.log(updated.name);

const frozen: Readonly<User> = ana;
// frozen.name = 'X'; // error: Cannot assign to 'name' because it is a read-only property
console.log(frozen.id);

Pick and Omit

Pick<T, Keys> creates a type with only the properties you name; Omit<T, Keys> creates one with all except the ones you name. Choosing one or the other depends on which list is shorter. The valuable part is that the derived type stays linked to the original: if you add a property to User, PublicUser = Omit<User, 'password'> includes it automatically and you do not have to remember to update anything.

typescript
interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

type PublicUser = Omit<User, 'password'>;
type UserSummary = Pick<User, 'id' | 'name'>;

function toPublic(user: User): PublicUser {
  const { password, ...rest } = user;
  void password; // intentionally dropped
  return rest;
}

const summary: UserSummary = { id: 1, name: 'Ana' };
console.log(toPublic({ id: 1, name: 'Ana', email: 'a@b.c', password: 'x' }), summary);

Record and others

Record<Keys, Value> describes an object whose keys are Keys and whose values are all of type Value. With a union of literals as keys, the compiler requires all of them to be present, which works as an exhaustiveness check. Other frequent utility types: ReturnType<typeof fn> gets a function's return type, Parameters<typeof fn> the tuple of its parameters, Awaited<T> the type a promise produces, NonNullable<T> removes null and undefined, and Exclude and Extract filter unions.

typescript
type Role = 'admin' | 'editor' | 'viewer';

const permissions: Record<Role, string[]> = {
  admin: ['read', 'write', 'delete'],
  editor: ['read', 'write'],
  viewer: ['read'],
  // missing a role here is a compile error
};

function createUser(name: string) {
  return { id: Math.floor(Math.random() * 1000), name, active: true };
}

type CreatedUser = ReturnType<typeof createUser>; // { id: number; name: string; active: boolean }
type WithoutViewer = Exclude<Role, 'viewer'>;      // 'admin' | 'editor'

const user: CreatedUser = createUser('Ana');
const r: WithoutViewer = 'admin';
console.log(permissions[r], user.active);

A common mistake is believing Readonly and Partial are deep. If User has an address property that is an object, Readonly<User> prevents reassigning address, but not changing address.city. For deep types you would have to write your own recursive type, something you will see in the next lesson. Also, Omit accepts any text as a key, even one that does not exist, without warning you of a typo: Omit<User, 'pasword'> gives no error. If you want more safety, write your own type with K extends keyof T, which rejects nonexistent keys.

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →