Asosiy matnga o'tish
ITIT Interview
TypeScript

Utility types

Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, NonNullable, ReturnType, Parameters va Awaited.

O'rganildi: 0 / 5
Progress

Bu nima?

Utility types — TypeScript'ga o'rnatilgan, mavjud turlardan yangi tur yasaydigan generic turlar. Ular bir xil turni qayta-qayta yozmaslikka yordam beradi.

interface User {
  id: number;
  name: string;
  email: string;
  role: 'admin' | 'user';
}

Obyekt turlari bilan

UtilityNatijaMisol
Partial<T>Barcha maydonlar ixtiyoriyYangilash (PATCH) ma'lumoti
Required<T>Barcha maydonlar majburiyTo'liq to'ldirilgan konfiguratsiya
Readonly<T>Barcha maydonlar readonlyO'zgarmas state
Pick<T, K>Faqat tanlangan maydonlarRo'yxatda ko'rsatiladigan qism
Omit<T, K>Tanlanganlardan tashqariYaratish formasi (id siz)
Record<K, V>K kalitli, V qiymatli obyektLug'atlar, xaritalar
function updateUser(id: number, changes: Partial<User>) {}
updateUser(1, { name: 'Vali' });

type UserPreview = Pick<User, 'id' | 'name'>;
type NewUser = Omit<User, 'id'>;

const labels: Record<User['role'], string> = {
  admin: 'Administrator',
  user: 'Foydalanuvchi',
};

Union turlar bilan

type Status = 'idle' | 'loading' | 'success' | 'error';

type Active = Exclude<Status, 'idle'>;            // 'loading' | 'success' | 'error'
type Done = Extract<Status, 'success' | 'error'>; // 'success' | 'error'
type Name = NonNullable<string | null | undefined>; // string

Funksiya turlari bilan

function createUser(name: string, age: number) {
  return { id: Date.now(), name, age };
}

type NewUserResult = ReturnType<typeof createUser>;   // { id: number; name: string; age: number }
type CreateArgs = Parameters<typeof createUser>;      // [name: string, age: number]

async function loadUser() { return { id: 1 }; }
type Loaded = Awaited<ReturnType<typeof loadUser>>;   // { id: number }

Bu kutubxona funksiyasining qaytish turi eksport qilinmagan bo'lsa, uni olish uchun juda qulay.

Birlashtirish

// id majburiy, qolganlari ixtiyoriy
type UserUpdate = Pick<User, 'id'> & Partial<Omit<User, 'id'>>;

Ichkarida qanday yozilgan

Utility'lar oddiy mapped va conditional turlar:

type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyExclude<T, U> = T extends U ? never : T;
type MyOmit<T, K extends keyof any> = MyPick<T, MyExclude<keyof T, K>>;

Intervyu savollari

Ushbu sahifada