Generic

النوع العام (Generic)

Intermediatetypescript1 min read
genericstype parametertype variable<T>generic type

Definition

A TypeScript feature that lets you write reusable code that works with any type, specified at the call site.

ميزة TypeScript تتيح كتابة كود قابل لإعادة الاستخدام يعمل مع أي نوع، يُحدَّد عند موقع الاستدعاء.

Why It Matters

useState<Project[]>([]) — the <Project[]> part is a generic. Understanding generics helps you correctly type your state, refs, and async functions.

useState<Project[]>([]) — الجزء <Project[]> هو نوع عام. فهم الأنواع العامة يساعدك على تصنيف حالتك ومراجعك ودوالك اللاتزامنية بشكل صحيح.

Full Definition

Generics allow functions, classes, and interfaces to work with different types while maintaining type safety. The type parameter (typically `<T>`) is a placeholder that gets resolved when you use the generic. React's useState<T>(), useRef<T>(), and most Next.js utility types use generics. Firestore's DocumentData and collection types also use generics.
تتيح الأنواع العامة للدوال والكلاسات والـinterfaces العمل مع أنواع مختلفة مع الحفاظ على سلامة النوع. معامل النوع (عادةً `<T>`) هو عنصر نائب يُحَل عند استخدام النوع العام. useState<T>() في React وuseRef<T>() ومعظم أنواع Next.js المساعدة تستخدم الأنواع العامة.

Example Usage

const [projects, setProjects] = useState<Project[]>([]); async function fetchDoc<T>(id: string): Promise<T | null>

const [projects, setProjects] = useState<Project[]>([]); async function fetchDoc<T>(id: string): Promise<T | null>

Knowledge Graph

Avoid these mistakes when using Generic:

1

Using `any` instead of a generic — defeats the purpose of TypeScript

2

Over-constraining generics with complex extends clauses when a simpler approach works

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 Generic.

Explain:
1. What is Generic and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Using `any` instead of a generic — defeats the purpose of TypeScript, Over-constraining generics with complex extends clauses when a simpler approach works
5. Best practices and production tips

Official Resources