TypeScript بيحل إيه؟
TypeScript هي JavaScript مع static type system و compiler/transpiler tooling. الكود النهائي الذي ينفذه browser JavaScript؛ types غالبًا تُحذف وقت compilation. لذلك TypeScript تساعدك تكتشف أخطاء أثناء التطوير لكنها لا تتحقق تلقائيًا من البيانات القادمة من network وقت التشغيل. interface User لا تمنع API من إرسال null أو string بدل number.
بالنسبة لمطور .NET، فكر فيها كطبقة compile-time contract تساعد IDE و refactoring و autocomplete. لكنها ليست C# بنظام runtime نفسه: structural typing بدل nominal typing في حالات كثيرة، و type erasure، و any يمكنه تعطيل الحماية، و nullability تعتمد على compiler options مثل strictNullChecks.
TypeScript: compile time مقابل runtime
Type Annotations و Type Inference
لو القيمة واضحة، compiler يستنتج النوع. أضف annotation عند حدود النظام أو لما inference غير كافٍ أو contract يحتاج وضوح. تجنب كتابة type مكرر لكل local variable؛ كثرة annotations قد تجعل refactoring متعبًا بدون قيمة.
const pageSize = 20; // inferred as 20 (literal) in const context
let currentPage = 1; // inferred as number
const title: string = "Orders";
function total(items: readonly number[]): number {
return items.reduce((sum, item) => sum + item, 0);
}شغّل strict: true في tsconfig قدر الإمكان. أهم الخيارات: strictNullChecks, noImplicitAny, strictFunctionTypes وغيرها. لا تعالج أخطاء strict بإضافة as any في كل مكان؛ افهم مصدر القيمة وحدد contract صحيح.
Interfaces و Type Aliases
interface ممتازة لوصف object contracts ويمكن أن تمتد أو تتوسع declaration merging في حالات معينة. type alias أوسع: unions، intersections، tuples، primitives، mapped/conditional types. لا توجد قاعدة مطلقة أن واحدة دائمًا أفضل؛ اختَر ما يعبّر عن المعنى بوضوح والتزم convention المشروع.
export interface CustomerDto {
id: string;
displayName: string;
email?: string;
}
export type OrderStatus = "Draft" | "Pending" | "Paid" | "Cancelled";
export interface OrderDto {
id: string;
customer: CustomerDto;
total: number;
status: OrderStatus;
}Optional property email?: string تعني property قد تكون غائبة، ولا تعني بالضرورة أن null مسموح. لو server يرجع null، عرّف email: string | null. راجع exactOptionalPropertyTypes لأنه يؤثر في الفرق بين omission و undefined.
Structural Typing و Excess Property Checks
TypeScript غالبًا structural: object يعتبر compatible لو شكله يحقق members المطلوبة، مش لأنه أعلن implements أو ورث class. ده يسهل interop لكنه قد يسمح بتمرير object أكبر من المطلوب. Excess property checks على object literals المباشرة تساعد تلتقط typos، لكنها ليست exact object types في كل الحالات.
interface HasId { id: string; }
const order = { id: 'O-1', total: 250, status: 'Paid' };
const entity: HasId = order; // compatible: it has an id
function printId(value: HasId) {
console.log(value.id);
}
printId(order);لا تستخدم structural typing كبديل عن validation أو domain ownership. لو identifier types المختلفة كلها string، ممكن بالخطأ تمرر CustomerId مكان OrderId. Branded types أو wrapper value objects تمنع بعض الخلط في compile time، لكنها تحتاج constructors/validation عند runtime boundary.
type Brand<T, Name extends string> = T & { readonly __brand: Name };
type CustomerId = Brand<string, 'CustomerId'>;
type OrderId = Brand<string, 'OrderId'>;
function customerId(value: string): CustomerId {
if (!value.trim()) throw new Error('Customer id is required');
return value as CustomerId;
}Union و Intersection و Literal Types
Union A | B تعني القيمة أحد الأنواع. Intersection A & B تجمع requirements. Literal unions مفيدة لتمثيل enum-like values القادمة من API، وتمنع strings العشوائية. لا تستخدم intersection لدمج shapes متعارضة؛ صمم model واضحًا.
type LoadState<T> =
| { kind: "idle" }
| { kind: "loading" }
| { kind: "success"; data: T }
| { kind: "error"; message: string };
function renderOrders(state: LoadState<OrderDto[]>) {
switch (state.kind) {
case "idle": return "Ready";
case "loading": return "Loading...";
case "success": return `${state.data.length} orders`;
case "error": return state.message;
}
}Discriminated union تمنع حالة مستحيلة مثل {loading:true, data:undefined, error:"..."}. وجود kind يتيح narrowing تلقائي. استخدم exhaustive check بـ never حتى compiler ينبهك لو أضفت state جديدة ونسيت branch.
function assertNever(value: never): never {
throw new Error(`Unexpected state: ${String(value)}`);
}Strict TypeScript: Nullability و Discriminated Unions
فعّل strict mode و strictNullChecks و noUncheckedIndexedAccess عند الإمكان. لا تستخدم ! لإخفاء null إلا لو عندك invariant مثبت. الـ discriminated union تجعل حالات UI واضحة بدل object فيه عشرات booleans يمكن أن تتعارض.
type LoadState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; message: string };
function renderProducts(state: LoadState<Product[]>): string {
switch (state.status) {
case "idle": return "Not started";
case "loading": return "Loading…";
case "success": return `${state.data.length} products`;
case "error": return state.message;
default: return assertNever(state);
}
}
function assertNever(value: never): never {
throw new Error(`Unhandled state: ${JSON.stringify(value)}`);
}Discriminated unions مفيدة للـ payment state و authentication state و async data. لا تستخدم enum/string union لمجرد الشكل؛ اختَر نموذجًا يمنع الجمع بين بيانات success و error في نفس الوقت. TypeScript لا تمنع كل runtime invalid state، لذلك parsing عند boundaries يظل مطلوبًا.
Branded Types: امنع خلط IDs المتشابهة
type Brand<T, Name extends string> = T & { readonly __brand: Name };
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
function parseUserId(raw: string): UserId {
if (!/^usr_[a-z0-9]+$/i.test(raw)) throw new Error('Invalid user id');
return raw as UserId;
}
function loadUser(id: UserId) { /* call typed API client */ }
const userId = parseUserId('usr_123');
loadUser(userId);
// loadUser(orderId) is rejected by the TypeScript compiler.Branding compile-time aid فقط؛ assertion داخل parser لا يثبت صحة البيانات إلا لأننا تحققنا قبلها. لا تضع as UserId في كل call site، وإلا فقدت الحماية. اجعل parser هو الطريق الوحيد من raw string إلى branded ID، واستخدم runtime authorization في backend بشكل مستقل.
Generics: كتابة reusable types من غير فقدان النوع
Generic type parameter يمثل نوعًا يختاره caller، ويحافظ على العلاقة بين input/output. لا تستخدم any[] في helper عام؛ استخدم T[] حتى يظل return type معروفًا. Constraints بـ extends تفرض capability محددة.
export interface ApiResponse<T> {
data: T;
requestId: string;
}
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
function byId<T extends { id: string }>(items: readonly T[], id: string) {
return items.find(item => item.id === id);
}لا تضع generics لمجرد أنها تبدو advanced. لو type parameter لا يظهر في أكثر من مكان ولا يحافظ على علاقة مفيدة، قد لا تحتاجه. Generic abstraction معقدة قد تصعّب error messages وقراءة Angular code.
Generics و Variance و Type Narrowing
Generics تربط type input بالـ output بدل any. T extends يضع constraint، و keyof و indexed access types يساعدان في APIs آمنة. TypeScript يستخدم structural typing؛ object متوافق إذا شكله يفي بال contract، وليس لأنه يرث class بعينها. Variance تظهر مع producer/consumer positions؛ لا تفترض أن IEnumerable<Dog> و IConsumer<Dog> يتصرفان بنفس الطريقة.
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
type ApiResult<T> =
| { ok: true; data: T }
| { ok: false; error: { code: string; message: string } };
function unwrap<T>(result: ApiResult<T>): T {
if (result.ok) return result.data; // discriminant narrows the union
throw new Error(result.error.message);
}لا تستخدم type assertions (as) لتسكيت compiler بلا runtime validation. API JSON غير موثوق حتى لو عرّفت له interface؛ استخدم schema validation أو parser عند boundary. unknown أفضل من any لأنه يجبرك على narrowing قبل الاستخدام.
Type Narrowing و Type Guards
Narrowing يحدث من خلال typeof, instanceof, equality checks، in operator، discriminant property أو custom type guard. استخدمه بدل casting أعمى. as UserDto لا يحول object ولا يتحقق من شكله؛ هو فقط يخبر compiler أن يثق بك.
function formatApiError(value: unknown): string {
if (value instanceof Error) return value.message;
if (typeof value === "string") return value;
if (typeof value === "object" && value !== null && "message" in value) {
const message = value.message;
if (typeof message === "string") return message;
}
return "An unexpected error occurred";
}في boundary مع API، ابدأ من unknown ثم validate. يمكن استخدام schema validation library مثل Zod/Valibot، أو manual parser بسيط للـ contracts الحرجة. لا تحول كل response إلى any وتفقد الفائدة الأساسية للغة.
unknown vs any
any يوقف معظم type checking ويسمح بأي property/method. unknown يقبل أي قيمة لكن يمنعك من استخدامها قبل narrowing. استخدم unknown ل catch values و JSON.parse والحدود غير الموثوقة. في TS الحديثة catch variable يكون unknown عند تفعيل useUnknownInCatchVariables.
const raw: unknown = JSON.parse('{"id":"42"}');
if (typeof raw === "object" && raw !== null && "id" in raw) {
const id = raw.id;
if (typeof id === "string") {
console.log(id.toUpperCase());
}
}الـ any قد يكون مقبولًا مؤقتًا عند دمج legacy library غير typed، لكن حاصر استخدامه في adapter صغير واكتب TODO أو type declaration. لا تجعل any ينتشر في application model.
Runtime Validation: Types لا تتحقق من JSON
الـ response القادمة من ASP.NET Core يمكن أن تتغير بسبب version mismatch أو proxy/cache bug أو data corruption أو malicious endpoint. Type assertion مثل response as OrderDto لا يفحص أي شيء. لو contract بسيط، اكتب parser يتحقق من required fields والأنواع. لو schema كبيرة ومتداخلة، schema validation library قد تقلل boilerplate وتوفر inferred types.
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function parseOrder(value: unknown): OrderDto {
if (!isRecord(value) ||
typeof value.id !== 'string' ||
typeof value.total !== 'number' ||
!['Pending', 'Paid', 'Cancelled'].includes(String(value.status))) {
throw new Error('Invalid OrderDto payload');
}
return {
id: value.id,
total: value.total,
status: value.status as OrderDto['status']
};
}Parser ده illustrative وليس universal schema validator: لازم تضيف bounds للـ number، currency rules، nested fields، dates، unknown properties policy و error paths حسب contract. لا تجعل validation logic متكررة في كل component؛ ضعها في API adapter أو generated client boundary.
TypeScript لا يتحقق من JSON وقت التشغيل
TypeScript types تُمحى عند transpilation. لو API رجعت { id: "not-a-guid", price: "free" }، فكتابة response as Product لا تتحقق من البيانات؛ هي فقط تُسكت compiler. حدود النظام تحتاج runtime validation أو parsing موثوق. هذا مهم خصوصًا للـ localStorage و URL params و webhooks و API responses.
type Product = { id: string; name: string; price: number };
function isProduct(value: unknown): value is Product {
if (typeof value !== "object" || value === null) return false;
const x = value as Record<string, unknown>;
return typeof x.id === "string"
&& typeof x.name === "string"
&& typeof x.price === "number"
&& Number.isFinite(x.price);
}في الكود السابق يجب أن تكون علامة الاقتباس في typeof x.price === "number" مزدوجة صحيحة؛ المقصود توضيح type guard. في تطبيق فعلي استخدم schema validator مثل Zod أو Valibot أو تحقق يدويًا، وارجع typed result بعد parsing. لا تخلط compile-time contract مع runtime guarantee.
TypeScript لا يعمل Runtime Validation
Interface و type alias لا يتحققان من JSON القادم من API؛ TypeScript types تُمحى عند compilation. لذلك const user = await response.json() as User مجرد assertion لا validation. عند حدود الثقة استخدم parser أو schema validator مثل Zod/Valibot أو manual type guard. تحقق من shape و range و enum values والحقول الاختيارية، ثم حوّل إلى domain model مناسب للواجهة.
type UserDto = { id: string; displayName: string };
function isUserDto(value: unknown): value is UserDto {
if (typeof value !== 'object' || value === null) return false;
const item = value as Record<string, unknown>;
return typeof item.id === 'string' && typeof item.displayName === 'string';
}
async function loadUser(): Promise<UserDto> {
const response = await fetch('/api/me');
if (!response.ok) throw new Error('Could not load user');
const payload: unknown = await response.json();
if (!isUserDto(payload)) throw new Error('Invalid API response');
return payload;
}لا تثق في browser storage أو URL query أو postMessage لمجرد أنك كتبت لها interface. اختبر malformed payloads و null و wrong primitive types و unknown enum values. حافظ على API contract versioning؛ client قد يتصل بخادم أحدث أو أقدم.
تقليل any و Assertions عبر Unknown و Type Guards
عندما تتعامل مع library قديمة أو JSON غير معروف، ابدأ بـ unknown ثم ضيق النوع عبر typeof و in و custom type guard أو schema parser. لا تحوّل any إلى كل النظام؛ اجعل escape hatch في adapter واحد ثم أخرج typed contract. assertions المتكررة علامة أن type model أو runtime validation ناقص.
استعمل satisfies للتحقق من أن object يفي contract مع الاحتفاظ بأدق inferred type، واستعمل as const للـ literal data الثابتة. لا تستخدمهما لتجميد runtime object أو للتحقق من payload. compiler يراجع source types فقط؛ runtime boundary تحتاج validation فعلية.
Utility Types
TypeScript توفر utilities جاهزة: `Partial كل properties optional، Required تجعلها required، Pick تختار fields، Omit تستبعد fields، Readonly يمنع reassignment وقت compile، Record dictionary، ReturnType وParameters` لاستخراج function types. استخدمها لتقليل duplication لكن لا تجعل DTO معقدًا بسلسلة transformations غامضة.
type CreateCustomer = Pick<CustomerDto, "displayName"> & {
email: string;
};
type UpdateCustomer = Partial<Pick<CustomerDto, "displayName" | "email">>;
type CustomerMap = Record<string, CustomerDto>;Partial لا تعني أن API تقبل أي patch تلقائيًا؛ لازم endpoint يحدد semantics: هل null يمسح الحقل؟ هل omission يعني no change؟ وهل empty string valid؟ TypeScript type لا يقرر server behavior.
Utility Types و API Contract Evolution
Pick و Omit و Partial و Required و Readonly تساعد على تشكيل view types، لكنها لا تستبدل DTO design. لا تستخدم Partial<Entity> كـ update request تلقائيًا؛ هذا قد يسمح بتعديل fields لا ينبغي للعميل لمسها. عرّف command DTO لكل operation، واستخدم discriminated unions لتمثيل حالات واضحة بدل object به عشر optional properties متعارضة.
type ChangeEmail = { kind: 'change-email'; email: string };
type ChangeDisplayName = { kind: 'change-name'; displayName: string };
type ProfileCommand = ChangeEmail | ChangeDisplayName;
function describe(command: ProfileCommand): string {
switch (command.kind) {
case 'change-email': return `Change email to ${command.email}`;
case 'change-name': return `Change name to ${command.displayName}`;
default: return assertNever(command);
}
}
function assertNever(value: never): never {
throw new Error(`Unhandled command: ${String(value)}`);
}استخدم exhaustive switch حتى compiler ينبهك عند إضافة variant. عند API evolution اجعل client يتعامل مع unknown enum values و optional fields بوعي. TypeScript type system لا يضمن توافق backend schema؛ contract tests أو generated clients/schema validation تقلل drift.
Type Design Checklist
قبل تعريف type اسأل: هل الحالة invalid ممكن تمثيلها؟ هل discriminated union أو branded type يمنع الخلط بين IDs؟ هل null/undefined معناهما مختلف؟ هل API payload validated؟ هل any يتسرب؟ هل utility type جعل كل الحقول optional بلا داعٍ؟ اجعل type names تعبر عن domain concept، لا عن شكل JSON فقط.
Branding قد يمنع خلط UserId و OrderId رغم أن الاثنين string، لكنه compile-time distinction فقط. لا تعتبره authorization أو validation. أضف constructor/parser يحول raw string إلى branded value بعد التحقق من format.
Classes و Access Modifiers
TypeScript classes تدعم public, protected, private, readonly, constructors و implements. private التقليدية compile-time restriction؛ ECMAScript #field private runtime field. Angular services عادة classes، لكن models غالبًا interfaces/types أبسط من classes لأن JSON serialization لا يعيد prototypes تلقائيًا.
export class Money {
private constructor(
public readonly minorUnits: number,
public readonly currency: string
) {}
static create(minorUnits: number, currency: string): Money {
if (!Number.isSafeInteger(minorUnits)) {
throw new Error("minorUnits must be a safe integer");
}
if (!/^[A-Z]{3}$/.test(currency)) {
throw new Error("currency must be an ISO-like code");
}
return new Money(minorUnits, currency);
}
}TypeScript structural typing تعني object قد يحقق interface من غير أن يرث class. implements يفحص contract وقت compile ولا يضيف runtime enforcement. لا تستخدم inheritance لمجرد مشاركة fields؛ composition/functions غالبًا أوضح.
Typing API Responses و async/await
Generic HttpClient في Angular يسمح بتحديد نوع response، لكنه type assertion فقط وليس runtime validation. اكتب DTO interfaces منفصلة عن UI view models عند الحاجة. Date القادمة من JSON تكون string عادة، مش Date object تلقائيًا؛ حولها صراحة. كذلك numeric values قد تتطلب formatting ولا تحولها إلى string قبل الحساب.
interface OrderApi {
getById(id: string): Promise<OrderDto>;
}
async function loadOrder(api: OrderApi, id: string): Promise<OrderDto> {
const order = await api.getById(id);
if (order.id !== id) {
throw new Error("API contract mismatch");
}
return order;
}استخدم `Promise
Async Types و Promise و Error Contracts
`Promise بدل رمي exceptions لكل حالة business متوقعة. لا تحول network failures إلى null` لأنك ستفقد الفرق بين not-found و offline و unauthorized.
type ApiResult<T> =
| { ok: true; value: T }
| { ok: false; kind: 'not-found' | 'conflict' | 'validation'; message: string };
async function findOrder(id: string): Promise<ApiResult<OrderDto>> {
// An adapter maps known HTTP statuses to explicit outcomes.
throw new Error('Implementation belongs in the HTTP service');
}في Angular، HttpClient ObservablecatchError يحول error channel، بينما retry قد يعيد الاشتراك وينفذ request ثانية. لا تضع retry لكل POST أو لكل 4xx. TypeScript types تساعدك تفرض التعامل مع union states، لكن network semantics لازم تفهمها.
tsconfig وقراءة أخطاء Compiler
راجع tsconfig قبل كتابة code: strict, noImplicitOverride, noFallthroughCasesInSwitch, noUncheckedIndexedAccess و exactOptionalPropertyTypes حسب المشروع. Angular CLI قد يوزع إعدادات base/app/spec؛ لا تعدل ملفًا من غير معرفة inheritance عبر extends.
{
"compilerOptions": {
"strict": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}عند ظهور compiler error، اقرأ النوع المتوقع والفعلي ومكان نشأته. لا تستخدم non-null assertion ! أو cast as لإسكات الرسالة قبل فهم invariant. لو array index قد يرجع undefined، تعامل مع الحالة بدل افتراض وجود العنصر. لو union لم يتم تضييقه، أضف guard منطقي.
tsconfig Strictness و Build Pipeline
فعّل strict تدريجيًا أو من البداية في المشروع الجديد؛ أهم ما يضيفه strictNullChecks و noImplicitAny و strictFunctionTypes. noUncheckedIndexedAccess يجعل الوصول إلى array/dictionary يعبر عن احتمال غياب القيمة. exactOptionalPropertyTypes يفرق بين property غير موجودة و property موجودة بقيمة undefined. لا تطفئ flags عند أول error؛ استخدم narrowing و types أدق.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true
}
}TypeScript compilation لا يشغّل tests ولا يضمن runtime payload correctness. pipeline يجب تشمل typecheck و lint و unit tests و bundle build. لا تخلط transpile-only mode مع type checking؛ بعض dev servers تتجاوز type checker لتحسين السرعة. اجعل CI هو gate النهائي.
Modules و Compiler Pipeline و Build Tooling
TypeScript compiler يقوم type checking ويحول syntax إلى JavaScript حسب target/module settings. Bundler مثل Angular CLI/esbuild يربط modules ويعمل optimization/tree-shaking/code splitting. لا تخلط compile errors مع bundler errors أو runtime errors. tsconfig قد يحتوي base config مع app/spec configs؛ استخدم tsc --showConfig لفهم config النهائي عند التشخيص.
Module resolution يحدد كيف import يتحول إلى file/package. في browser apps غالبًا bundler يفسر aliases و package exports. تجنب path aliases تشير إلى ملفات خارج workspace أو تسبب circular imports. خليك واضحًا بين type-only imports (import type) و runtime imports عندما يفيد ذلك في تقليل cycles و bundle dependencies.
import type { OrderDto } from './orders.models';
import { formatOrderTotal } from './orders.formatters';
export function orderLabel(order: OrderDto): string {
return `${order.id}: ${formatOrderTotal(order.total)}`;
}Compiler Boundary و Declaration Files
Declaration files (.d.ts) تصف types لمكتبة JavaScript ولا تضيف runtime implementation. لو declaration غير دقيقة، قد يثق compiler في contract غير صحيح. راجع package types/version alignment، ولا تكتب declare module واسعًا يحول مكتبة كاملة إلى any. استخدم module augmentation فقط عندما تضيف contract حقيقيًا، واختبر integration مع runtime package الفعلية.
اختبر فهمك
هل TypeScript تمنع API من إرسال شكل بيانات خاطئ وقت runtime؟
متى تستخدم unknown بدل any؟
ما فائدة discriminated union؟
هل interface و type متطابقان؟
هل HttpClient.get<OrderDto> يتحقق من JSON؟
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
خريطة التغطية: 12 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.