⏱️4 min read · 763 words
تختبر أسئلة مقابلة TypeScript في عام 2026 مدى فهمك لنظام الكتابة والأدوية العامة والأنماط المتقدمة والتكامل مع React وNode.js. يغطي هذا الدليل الأسئلة الأكثر شيوعًا حول TypeScript على المستويين المبتدئ والعليا.
أسئلة TypeScript الأساسية
1. ما الفرق بين الواجهة والنوع المستعار؟
// Interface — can be merged (declaration merging), preferred for objects
interface User {
id: number;
name: string;
}
// Extend interface
interface AdminUser extends User {
role: 'admin';
}
// Declaration merging (unique to interface)
interface User {
email: string; // adds to existing interface
}
// Type alias — more flexible, supports unions and intersections
type ID = string | number;
type Status = 'pending' | 'active' | 'inactive';
type ApiResponse<T> = { data: T; error: string | null; };
// Intersection
type AuthUser = User & { token: string };
// When to use:
// interface: for objects, especially when extending or merging
// type: for unions, intersections, primitives, tuples
2. اشرح الأدوية العامة بمثال حقيقي
// Generic function — works with any type
function first<T>(items: T[]): T | undefined {
return items[0];
}
const num = first([1, 2, 3]); // type: number | undefined
const str = first(['a', 'b']); // type: string | undefined
// Generic with constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: 'Alice', age: 30 };
const name = getProperty(user, 'name'); // type: string
// getProperty(user, 'foo'); // Error! 'foo' not in keyof User
// Generic class
class Repository<T extends { id: number }> {
private items: T[] = [];
add(item: T): void { this.items.push(item); }
findById(id: number): T | undefined {
return this.items.find(i => i.id === id);
}
getAll(): T[] { return [...this.items]; }
}
const userRepo = new Repository<User>();
userRepo.add({ id: 1, name: 'Alice' });
3. ما هي أنواع المرافق؟ أعط أمثلة
interface User {
id: number;
name: string;
email: string;
password: string;
role: 'admin' | 'user';
}
// Partial — all optional
type UserUpdate = Partial<User>;
// Required — all required (reverse of Partial)
type StrictUser = Required<User>;
// Pick — select fields
type PublicUser = Pick<User, 'id' | 'name' | 'email'>;
// Omit — exclude fields
type CreateUserInput = Omit<User, 'id'>;
type SafeUser = Omit<User, 'password'>;
// Readonly
type ImmutableUser = Readonly<User>;
// Record — map type
type UsersByRole = Record<'admin' | 'user', User[]>;
// Extract / Exclude
type StringOrNumber = string | number | boolean;
type OnlyString = Extract<StringOrNumber, string>; // string
type NoBoolean = Exclude<StringOrNumber, boolean>; // string | number
// ReturnType / Parameters
async function fetchUser(id: number): Promise<User> { /* ... */ return {} as User; }
type FetchResult = Awaited<ReturnType<typeof fetchUser>>; // User
type FetchArgs = Parameters<typeof fetchUser>; // [number]
// NonNullable
type MaybeUser = User | null | undefined;
type DefiniteUser = NonNullable<MaybeUser>; // User
4. اشرح النوع “غير المعروف” مقابل “أي”.
// any — disables type checking (avoid!)
let a: any = 'hello';
a.toUpperCase(); // OK (even if string)
a.nonExistent(); // No error! Dangerous!
// unknown — type-safe alternative to any
let b: unknown = 'hello';
// b.toUpperCase(); // Error! Must narrow first
// b.nonExistent(); // Error!
// Must narrow unknown before use
if (typeof b === 'string') {
b.toUpperCase(); // OK — narrowed to string
}
// Real use case: typed error handling
async function fetchData(): Promise<unknown> {
const r = await fetch('/api/data');
return r.json();
}
const data = await fetchData();
if (typeof data === 'object' && data !== null && 'users' in data) {
console.log((data as { users: User[] }).users);
}
5. ما هي الأنواع المعينة؟
// Map over keys of an existing type
type Optional<T> = {
[K in keyof T]?: T[K];
};
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
// Conditional mapped type — change type based on condition
type NonNullableProps<T> = {
[K in keyof T]-?: NonNullable<T[K]>; // -? removes optional
};
// Key remapping (TS 4.1+)
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// { getId: () => number; getName: () => string; ... }
6. أنواع القالب الحرفي
type EventName = 'click' | 'focus' | 'blur';
type Handler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus' | 'onBlur'
type Route = '/users' | '/posts' | '/comments';
type ApiRoute = `${Route}/${number}`;
// '/users/1' | '/posts/2' etc.
// Real use case: CSS properties
type Side = 'top' | 'bottom' | 'left' | 'right';
type CSSPadding = `padding-${Side}`;
// 'padding-top' | 'padding-bottom' | 'padding-left' | 'padding-right'
// Event emitter with type safety
type Events = {
'user:created': { user: User };
'order:placed': { orderId: string; total: number };
};
declare function emit<K extends keyof Events>(event: K, data: Events[K]): void;
emit('user:created', { user: { id: 1, name: 'Alice' } }); // type-safe!
7. النقابات التمييزية
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function handleResult<T>(result: Result<T>) {
if (result.success) {
console.log(result.data); // TypeScript knows: data exists
} else {
console.error(result.error); // TypeScript knows: error exists
}
}
// Shape discriminated union
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return 0.5 * shape.base * shape.height;
}
}
نجاح مقابلة TypeScript: فهم نظام الكتابة بعمق (وليس فقط بناء الجملة)، وشرح سبب تمكين الأدوية العامة لإعادة استخدام التعليمات البرمجية، ومعرفة أنواع المرافق الشائعة عن ظهر قلب، وإظهار الأنواع الشرطية + المعينة للأسئلة المتقدمة. تختبر مقابلات TypeScript بشكل متزايد تكامل React+TypeScript – تدرب على كتابة الخطافات والدعائم ومعالجات الأحداث.
🔗 Share this article
✍️ Leave a Comment