index signature تصف نوع الخصائص عندما لا تعرف أسماءها مسبقاً — نمذجة القواميِيس/الخرائط حيث تكون المفاتيح ديناميكية.
ts
interface StringMap {
[: ]: ;
}
: = { : , : };
scores. = ;
scores.;
scores.;
index signature تصف نوع الخصائص عندما لا تعرف أسماءها مسبقاً — نمذجة القواميِيس/الخرائط حيث تكون المفاتيح ديناميكية.
interface StringMap {
[: ]: ;
}
: = { : , : };
scores. = ;
scores.;
scores.;
مع index signature عادي، يفترض المترجم أن كل مفتاح موجود، لذا scores.typo يُكتَب كـ number حتى لو كان في الواقع undefined في وقت التشغيل. تفعيل noUncheckedIndexedAccess يصلح هذا:
// with noUncheckedIndexedAccess: true
scores.math; // number | undefined → forces you to handle the missing case
interface Config {
name: string; // known property
[key: string]: string | number; // plus arbitrary extra keys
}
جميع الخصائص المسماة يجب أن تكون قابلة للإسناد إلى نوع قيمة index signature.
type Scores = Record<string, number>; // same as the index signature
type Roles = Record<"admin" | "user", boolean>; // constrained keys
Record هو الاختصار الاصطلاحي ويدعم اتحاد مفاتيح مقيد، وهو ما لا يستطيعه [key: string] عادي.
index signatures تنمذج كائنات بمفاتيح حقيقية ديناميكية (جداول البحث، الذاكرة المؤقتة، خرائط JSON المحللة).
اعرف تحذير الأمان (noUncheckedIndexedAccess) وفضّل Record<K, V> من أجل الوضوح — وفضّل Map عندما تكون المفاتيح مفتوحة حقاً وتريد دلالات التكرار/الحجم الحقيقية.