Seriya: TypeScript Basics Dars 87

Request types

TypeScript'da so'rov type'lari: entity'dan Omit, Partial va Pick bilan create/update/query type'larini yasash, Product API funksiyalari va bitta manbadan avtomatik yangilanish.

87-dars

Request types

Serverga yuboriladigan ma'lumot ham type'lanadi: body, query parametrlar va URL parametrlar. Asosiy hiyla: bu type'larni noldan yozmasdan, mavjud entity type'idan utility type'lar (Omit, Partial, Pick — 63–65-darslar) bilan yasash.

Bazaviy entity

type Product = {
  id: number;
  title: string;
  price: number;
  categoryId: number;
  createdAt: string;
};

1. Create request: Omit

Yangi mahsulot yaratganda id va createdAt'ni server o'zi beradi, ularni yubormaysiz:

type CreateProductRequest = Omit<Product, "id" | "createdAt">;
// { title: string; price: number; categoryId: number }

2. Update request: Partial

Tahrirlashda faqat o'zgargan maydonlar yuboriladi:

type UpdateProductRequest = Partial<CreateProductRequest>;
// { title?: string; price?: number; categoryId?: number }

3. Query parametrlar

type ProductQuery = {
  page?: number;
  search?: string;
  sort?: "price_asc" | "price_desc" | "newest";
};

sort'ga faqat 3 ta qiymat ruxsat, xato yozsangiz TS ushlaydi.

Real misol: Product API funksiyalari

function toQueryString(query: ProductQuery): string {
  const params = new URLSearchParams();
  for (const [key, value] of Object.entries(query)) {
    if (value !== undefined) params.set(key, String(value));
  }
  return params.toString();
}

export const productApi = {
  list(query: ProductQuery) {
    return fetchJson<Paginated<Product>>(`/api/products?${toQueryString(query)}`);
  },

  create(body: CreateProductRequest) {
    return fetchJson<Product>("/api/products", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
  },

  update(id: number, body: UpdateProductRequest) {
    return fetchJson<Product>(`/api/products/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
  },
};

Ishlatish:

productApi.list({ page: 1, sort: "newest" }); // ✅
productApi.list({ sort: "cheap" });
// ❌ Type '"cheap"' is not assignable to type '"price_asc" | "price_desc" | "newest" | undefined'.

productApi.create({ title: "Telefon", price: 3_000_000, categoryId: 2 }); // ✅
productApi.create({ title: "Telefon" });
// ❌ Property 'price' is missing in type '{ title: string; }' but required in type 'CreateProductRequest'.

productApi.update(5, { price: 2_500_000 }); // ✅ faqat narx
productApi.update(5, { id: 10 });
// ❌ Object literal may only specify known properties, and 'id' does not exist in type 'UpdateProductRequest'.

Afzalligi

Product'ga yangi maydon qo'shsangiz (masalan stock: number), CreateProductRequest va UpdateProductRequest avtomatik yangilanadi. Qo'lda 3 joyni o'zgartirish shart emas — bitta manba (Product) o'zgaradi, qolgani ergashadi.

Eslab qolish uchun

Holat Type
Yaratish Omit<Entity, "id" | "createdAt">
Tahrirlash Partial<CreateRequest>
Bir nechta maydon Pick<Entity, "title" | "price">
Query Ixtiyoriy maydonlar + literal union