Type Guard

حارس النوع (Type Guard)

Intermediatetypescript1 min read
type narrowinginstanceoftypeof checkis keywordtype predicate

Definition

A TypeScript pattern for narrowing a broad type to a specific subtype at runtime, using runtime checks.

نمط TypeScript لتضييق نوع واسع إلى نوع فرعي محدد في وقت التشغيل باستخدام فحوصات وقت التشغيل.

Why It Matters

When fetching data from Firestore or an API, the raw type is `unknown` or `any`. Type guards let TypeScript narrow it to your domain types safely.

عند جلب البيانات من Firestore أو API، النوع الخام هو `unknown` أو `any`. حراس النوع تتيح لـTypeScript تضييقه إلى أنواع المجال بأمان.

Full Definition

Type guards narrow the type of a variable in a conditional block. Built-in guards: `typeof value === 'string'`, `value instanceof Error`, `'id' in object`. Custom type predicates: `function isProject(x: unknown): x is Project`. Type narrowing is essential when handling Firestore document data (typed as `DocumentData`) or API responses (typed as `unknown`).
حراس النوع تضيّق نوع المتغير في كتلة شرطية. الحراس المدمجون: `typeof value === 'string'` و`value instanceof Error` و`'id' in object`. المسندات المخصصة: `function isProject(x: unknown): x is Project`.

Example Usage

function isAdminGuardError(x: unknown): x is { response: Response } { return typeof x === 'object' && x !== null && 'response' in x; }

function isAdminGuardError(x: unknown): x is { response: Response } { return typeof x === 'object' && x !== null && 'response' in x; }

Knowledge Graph

Avoid these mistakes when using Type Guard:

1

Using `as Type` (type assertion) instead of a type guard — assertions bypass TypeScript's checks and can cause runtime errors

Sign in to unlock guided AI explanations from AI Teacher.

Generate a Prompt

Copy this prompt and use it directly with any AI model — no setup needed.

Ready-to-Use Prompt
Help me build a project using Type Guard.

Explain:
1. What is Type Guard and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Using `as Type` (type assertion) instead of a type guard — assertions bypass TypeScript's checks and can cause runtime errors
5. Best practices and production tips

Official Resources