أهلاً بك في الدرس السادس والأخير من وحدة "أساسيات TypeScript العملية". في الدرس السابق، استكشفنا قوة Generics، وتعلمنا كيف نكتب دوال وواجهات مرنة وقابلة لإعادة الاستخدام. لقد بنيت أدوات مساعدة مثل createPaginatedResponse<T>، والتي يمكنها العمل مع أي نوع من البيانات مع الحفاظ على سلامة الأنواع (type safety).
اليوم، سنبني على هذا الأساس وننتقل إلى مستوى أعلى من الإنتاجية. فبدلاً من بناء كل نوع عام (generic type) من الصفر، يوفر TypeScript مجموعة من "الأنواع المساعدة" (Utility Types) الجاهزة. هذه الأنواع هي في جوهرها أنواع عامة قوية ومعدة مسبقًا لحل المشاكل الأكثر شيوعًا في تحويل الأنواع والتلاعب بها. إتقانها هو جزء أساسي من قاعدة 80/20: فهي تمثل 20% من الأدوات التي ستحل 80% من مهام التعامل مع الأنواع التي تواجهها يوميًا.
في هذا الدرس، ستتعلم كيفية استخدام أنواع مساعدة مثل Partial، Pick، Omit، وReturnType لإنشاء أنواع جديدة من أنواع موجودة، مما يمنع تكرار الكود ويجعل قاعدة الكود الخاصة بك أكثر قوة وقابلية للصيانة.
المشكلة: انفجار الأنواع (Type Explosion)
في أي تطبيق حقيقي، نادرًا ما يكون لديك نوع بيانات واحد فقط. عادةً ما تحتاج إلى أشكال مختلفة من نفس نموذج البيانات الأساسي. لنأخذ كيان User كمثال:
- الكائن الكامل:
Userمع جميع الخصائص (id,name,email,createdAt, etc.) عند جلبه من قاعدة البيانات. - لإنشاء مستخدم جديد: تحتاج إلى كل شيء ما عدا
idوcreatedAt، لأنها تُنشأ بواسطة الخادم. - لتحديث مستخدم: تحتاج إلى أن تكون جميع الخصائص اختيارية، لأنك قد تحدِّث خاصية واحدة فقط (
nameمثلاً). - لعرض ملخص: قد تحتاج فقط إلى
idوname.
إذا قمت بتعريف واجهة منفصلة لكل حالة من هذه الحالات يدويًا، ستواجه كابوسًا في الصيانة.
Understanding TypeScript Utility Types: Pick, Omit, and ...
يشرح هذا المقال من BetterStack المشكلة بشكل مثالي.
اقرأ قسم "مشكلة تكرار الأنواع". لاحظ كيف أن تعريف CreateUserRequest و UpdateUserRequest و UserSummary يدويًا يؤدي إلى أنواع غير متزامنة عندما يتغير النوع الأساسي User. هذا هو بالضبط ما نريد تجنبه.
الحل: اشتقاق الأنواع باستخدام Utility Types
الأنواع المساعدة تسمح لنا باشتقاق (derive) هذه الأشكال المختلفة من نوع أساسي واحد، مما يضمن أن جميع الأنواع تظل متزامنة تلقائيًا. لنستكشف أهم هذه الأنواع.
Pick<T, K> و Omit<T, K>: للاختيار والاستبعاد
هذان هما النوعان المساعدان الأكثر استخدامًا.
Pick<Type, Keys>: ينشئ نوعًا جديدًا عن طريق اختيار مجموعة من الخصائص (Keys) من النوع الأصلي (Type).Omit<Type, Keys>: ينشئ نوعًا جديدًا عن طريق حذف مجموعة من الخصائص (Keys) من النوع الأصلي (Type).
لنحل مشكلة User التي طرحناها:
interface User {
id: string;
name: string;
email: string;
createdAt: Date;
role: 'admin' | 'user';
}
// 1. نوع لإنشاء مستخدم جديد (بدون id و createdAt)
type CreateUserPayload = Omit<User, 'id' | 'createdAt'>;
// Result: { name: string; email: string; role: 'admin' | 'user'; }
// 2. نوع لملخص المستخدم (فقط id و name)
type UserSummary = Pick<User, 'id' | 'name'>;
// Result: { id: string; name: string; }
لاحظ كيف أننا لم نكرر أي تعريف خاصية. إذا أضفنا خاصية جديدة إلى User، فإن CreateUserPayload سيحتوي عليها تلقائيًا (لأننا لم نستبعدها)، بينما سيتجاهلها UserSummary.
You are a Junior Dev if You Don’t Know These 18 TypeScript Utility Types
يقدم هذا الفيديو من Web Dev Simplified شرحًا واضحًا وعمليًا جدًا لـ Pick و Omit.
شاهد الجزء الذي يغطي Pick ثم الجزء الخاص بـ Omit. ركز على كيف أن استخدام هذه الأنواع المساعدة يربط كل شيء بالنوع الأساسي User، مما يجعل التعديلات المستقبلية أسهل بكثير.
Partial<T> و Required<T>: لجعل الخصائص اختيارية أو إلزامية
Partial<Type>: ينشئ نوعًا جديدًا تكون فيه جميع خصائص النوع الأصليTypeاختيارية (?). هذا مثالي لعمليات التحديث (PATCH API requests).Required<Type>: عكسPartial. يجعل جميع الخصائص إلزامية، ويزيل أي علامة اختيارية (?).
// 3. نوع لتحديث المستخدم (كل الخصائص اختيارية)
type UpdateUserPayload = Partial<User>;
// Result: { id?: string; name?: string; email?: string; ... }
interface DraftPost {
title?: string;
content?: string;
}
// 4. نوع للتأكد من أن المسودة مكتملة قبل النشر
type PublishablePost = Required<DraftPost>;
// Result: { title: string; content: string; }
Partial مفيد للغاية في واجهات برمجة التطبيقات. عندما يرسل المستخدم طلب PATCH لتحديث اسمه فقط، فإن الجسم (body) المرسل سيكون { "name": "New Name" }. استخدام Partial<User> يصف هذا الشكل تمامًا.
TypeScript's Utility Types... Blazing fast
يقدم Matt Pocock لمحة سريعة وممتازة عن هذه الأنواع.
شاهد هذا الجزء الذي يغطي Partial و Required. ثم شاهد الجزء التالي الذي يوضح Omit و Pick وكيف يمكن دمجها معًا.
ReturnType<T> و Parameters<T>: لاشتقاق الأنواع من الدوال
هذه الأدوات قوية بشكل لا يصدق للحفاظ على التزامن بين الدوال التي تستدعي بعضها البعض.
ReturnType<Type>: يستخرج نوع القيمة المُرجعة من دالة.Parameters<Type>: يستخرج أنواع معاملات الدالة على شكلtuple(مصفوفة ذات طول وأنواع محددة).
function createProduct(name: string, price: number) {
return { id: `prod_${Math.random()}`, name, price, inStock: true };
}
// استخراج نوع القيمة المرجعة
type Product = ReturnType<typeof createProduct>;
// Result: { id: string; name: string; price: number; inStock: boolean; }
// استخراج أنواع المعاملات
type ProductCreationArgs = Parameters<typeof createProduct>;
// Result: [name: string, price: number]
الفائدة هنا هائلة. إذا قمت بتغيير ما تعيده دالة createProduct (مثلاً، أضفت خاصية category)، فإن نوع Product سيتم تحديثه تلقائيًا. لا حاجة لتغيير أي شيء يدويًا. هذا مفيد جدًا عند التعامل مع دوال من مكتبات خارجية لا تقوم بتصدير (export) أنواع الإرجاع الخاصة بها.
The Ultimate Guide to TypeScript Utility Types
يحتوي هذا الدليل الشامل على أمثلة ممتازة لهذه الأنواع المساعدة.
اقرأ قسم "Function Utilities". ركز على مثال ReturnType وكيفية استخدامه مع مكتبة خارجية. ثم انظر إلى مثال Parameters الذي يوضح حالة استخدام "تغليف دالة" (function wrapping)، وهي حالة شائعة جدًا.
ملخص مرئي
هذا الجدول يلخص الأنواع المساعدة الأكثر شيوعًا التي ناقشناها وحالات استخدامها النموذجية.

التطبيق العملي: بناء أنواع لكيان المنتج
حان الوقت الآن لتطبيق هذه المفاهيم. ستقوم بإنشاء مجموعة كاملة من الأنواع لكيان Product باستخدام الأنواع المساعدة فقط، مما يضمن أن يكون لديك مصدر حقيقة واحد (single source of truth).
مهمتك: افتح مشروع ts-project-setup، وقم بتعديل ملف src/index.ts.
- افتح
src/index.tsوامسح كل الكود الموجود فيه. - أضف الكود التالي. مهمتك هي استبدال
anyبالنوع المساعد المناسب مع المعاملات الصحيحة.
// src/index.ts
// =================================================================
// SINGLE SOURCE OF TRUTH: The base Product interface
// =================================================================
interface Product {
id: string;
name: string;
description: string;
price: number;
tags: string[];
inStock: boolean;
createdAt: Date;
updatedAt: Date;
}
// =================================================================
// DERIVED TYPES: Create variations using Utility Types
// =================================================================
// TODO 1: Use a utility type to create a type for the data needed to CREATE a product.
// We should OMIT `id`, `createdAt`, and `updatedAt` as they are generated by the server.
type ProductCreationData = any; /* <-- Replace 'any' with the correct utility type */
// TODO 2: Use a utility type to create a type for UPDATING a product.
// The update payload should be based on `ProductCreationData`, but all fields should be OPTIONAL.
// This is for PATCH requests where a client might only send one field to update.
type ProductUpdateData = any; /* <-- Replace 'any' with the correct utility type */
// TODO 3: Use a utility type for a product preview card in a UI.
// We only need to PICK `id`, `name`, and `price`.
type ProductPreview = any; /* <-- Replace 'any' with the correct utility type */
// =================================================================
// FUNCTION SIGNATURES using derived types
// =================================================================
// This function simulates creating a product in the database.
function createProduct(data: ProductCreationData): Product {
const now = new Date();
return {
id: `prod_${Math.random().toString(36).slice(2)}`,
createdAt: now,
updatedAt: now,
...data,
};
}
// TODO 4: Get the return type of the `createProduct` function automatically.
// This ensures that if `createProduct` changes its return structure, this type updates too.
type CreatedProduct = any; /* <-- Replace 'any' with the correct utility type */
// TODO 5: Create a type representing an object where keys are product IDs (string)
// and values are the full Product object. This is a common pattern for caching.
// HINT: We used this utility type in the previous lesson.
type ProductMap = any; /* <-- Replace 'any' with the correct utility type */
// =================================================================
// TESTING: Hover over these variables to check your work.
// =================================================================
// `newProductData` should enforce that `name`, `description`, etc. are provided.
const newProductData: ProductCreationData = {
name: 'Cloudflare T-Shirt',
description: 'A comfy shirt for edge computing fans.',
price: 25.00,
tags: ['clothing', 'swag'],
inStock: true,
};
// `updatePayload` should allow providing only a subset of fields.
const updatePayload: ProductUpdateData = {
price: 22.50,
inStock: false,
};
// `product` should have the full `Product` structure.
const product: CreatedProduct = createProduct(newProductData);
// `preview` should only have `id`, `name`, and `price`.
const preview: ProductPreview = {
id: product.id,
name: product.name,
price: product.price,
};
// const wrongPreview: ProductPreview = product; // This should be an error!
// `productCache` should be a dictionary of products.
const productCache: ProductMap = {
[product.id]: product,
};
console.log('New Product Data:', newProductData);
console.log('Update Payload:', updatePayload);
console.log('Created Product:', product);
console.log('Product Preview:', preview);
console.log('Product Cache:', productCache);
هل تحتاج إلى مساعدة؟
اضغط هنا لرؤية الحل
// src/index.ts
// =================================================================
// SINGLE SOURCE OF TRUTH: The base Product interface
// =================================================================
interface Product {
id: string;
name: string;
description: string;
price: number;
tags: string[];
inStock: boolean;
createdAt: Date;
updatedAt: Date;
}
// =================================================================
// DERIVED TYPES: Create variations using Utility Types
// =================================================================
// TODO 1: Use a utility type to create a type for the data needed to CREATE a product.
// We should OMIT `id`, `createdAt`, and `updatedAt` as they are generated by the server.
type ProductCreationData = Omit<Product, 'id' | 'createdAt' | 'updatedAt'>;
// TODO 2: Use a utility type to create a type for UPDATING a product.
// The update payload should be based on `ProductCreationData`, but all fields should be OPTIONAL.
// This is for PATCH requests where a client might only send one field to update.
type ProductUpdateData = Partial<ProductCreationData>;
// TODO 3: Use a utility type for a product preview card in a UI.
// We only need to PICK `id`, `name`, and `price`.
type ProductPreview = Pick<Product, 'id' | 'name' | 'price'>;
// =================================================================
// FUNCTION SIGNATURES using derived types
// =================================================================
// This function simulates creating a product in the database.
function createProduct(data: ProductCreationData): Product {
const now = new Date();
return {
id: `prod_${Math.random().toString(36).slice(2)}`,
createdAt: now,
updatedAt: now,
...data,
};
}
// TODO 4: Get the return type of the `createProduct` function automatically.
// This ensures that if `createProduct` changes its return structure, this type updates too.
type CreatedProduct = ReturnType<typeof createProduct>;
// TODO 5: Create a type representing an object where keys are product IDs (string)
// and values are the full Product object. This is a common pattern for caching.
// HINT: We used this utility type in the previous lesson.
type ProductMap = Record<string, Product>;
// =================================================================
// TESTING: Hover over these variables to check your work.
// =================================================================
// `newProductData` should enforce that `name`, `description`, etc. are provided.
const newProductData: ProductCreationData = {
name: 'Cloudflare T-Shirt',
description: 'A comfy shirt for edge computing fans.',
price: 25.00,
tags: ['clothing', 'swag'],
inStock: true,
};
// `updatePayload` should allow providing only a subset of fields.
const updatePayload: ProductUpdateData = {
price: 22.50,
inStock: false,
};
// `product` should have the full `Product` structure.
const product: CreatedProduct = createProduct(newProductData);
// `preview` should only have `id`, `name`, and `price`.
const preview: ProductPreview = {
id: product.id,
name: product.name,
price: product.price,
};
// const wrongPreview: ProductPreview = product; // This should be an error because `product` has extra fields!
// `productCache` should be a dictionary of products.
const productCache: ProductMap = {
[product.id]: product,
};
console.log('New Product Data:', newProductData);
console.log('Update Payload:', updatePayload);
console.log('Created Product:', product);
console.log('Product Preview:', preview);
console.log('Product Cache:', productCache);
بعد إكمال الكود، شغل خادم التطوير (npm run dev). الأهم من ذلك، تفاعل مع الكود في محرر النصوص. مرر الفأرة فوق كل نوع ومتغير قمت بإنشائه ولاحظ كيف يعرض المحرر النوع المشتق بدقة. جرب إضافة خاصية جديدة إلى واجهة Product ولاحظ كيف أن بعض الأنواع المشتقة تتضمنها تلقائيًا والبعض الآخر لا يتأثر، كل ذلك دون أي تدخل يدوي. هذا هو جوهر كتابة كود TypeScript قوي وقابل للصيانة.
خلاصة الدرس
لقد أتممت اليوم وحدة "أساسيات TypeScript العملية" بإتقان واحدة من أكثر ميزاته إنتاجية. لقد تعلمت كيف تتوقف عن تعريف الأنواع بشكل متكرر والبدء في اشتقاقها بذكاء.
النقاط الرئيسية:
- لا تكرر نفسك (DRY): الأنواع المساعدة هي تطبيق مبدأ DRY على نظام الأنواع في TypeScript.
PickوOmitهما أدواتك الأساسية لتشكيل أنواع الكائنات عن طريق اختيار أو استبعاد الخصائص.Partialلا غنى عنه لنمذجة بيانات التحديث (update payloads)، مما يجعل جميع الخصائص اختيارية.ReturnTypeوParametersيحافظان على تزامن أنواعك مع توقيعات الدوال، مما يقلل من الأخطاء عند إعادة بناء الكود.- كل هذه الأدوات تعمل معًا لإنشاء نظام أنواع قوي ومرن يعتمد على مصدر حقيقة واحد.
الدرس القادم
لقد بنيت الآن أساسًا متينًا في TypeScript. أنت جاهز للانتقال من التعامل مع البيانات بشكل متزامن إلى العالم الحقيقي للشبكات وواجهات برمجة التطبيقات، حيث كل شيء غير متزامن. في الدرس القادم، "البرمجة غير المتزامنة المتقدمة في TypeScript"، سنتعمق في event loop، ونحول الكود القديم المعتمد على callbacks إلى Promises، وننتقل إلى async/await الأنيق. سنقوم بإجراء طلبات fetch حقيقية لواجهات برمجة التطبيقات، ونتعلم كيفية التعامل مع عمليات متعددة في نفس الوقت. هذا هو الجسر الذي سينقلنا مباشرة إلى بناء أول واجهة برمجة تطبيقات خاصة بنا باستخدام Hono.