Introduction to Index Signatures
JavaScript objects can contain properties whose names are determined at runtime. For example, an application might store user preferences, language translations, product attributes, or configuration values in an object where the available keys are not known in advance.
TypeScript index signatures allow you to describe these dynamic objects by specifying which kinds of keys are permitted and what types their values must have. Instead of declaring every possible property individually, you define a rule that applies to properties accessed through the specified key type.
Index signatures are useful when working with dictionaries, lookup tables, dynamic configuration, metadata, and objects containing a variable collection of properties. They provide flexibility while preserving type checking for property access and assignment.
1. Creating Your First Index Signature
An index signature appears inside an object type, interface, or class. It specifies a key type and the expected value type for properties accessed through that key.
interface StringDictionary {
[key: string]: string;
}
const settings: StringDictionary = {
theme: "dark",
language: "English",
region: "Asia"
};
settings.timezone = "IST";
console.log(settings.theme);
console.log(settings.timezone);
The expression [key: string]: string is an index signature. It means that string-keyed properties must have string values.
The names key and string are part of the index signature declaration, not a property that must exist on the object. You can use another descriptive parameter name, such as [propertyName: string]: string, without changing the meaning.
Because additional property names are allowed, settings can contain theme, language, region, timezone, or other string-keyed settings. Their values must still be strings.
If you attempt to assign a number to one of these properties, TypeScript reports an error because the value does not satisfy the index signature.
const settings: StringDictionary = {
theme: "dark",
language: "English"
};
// Compile-time error:
// settings.retryCount = 3;
Index signatures are best suited to objects where flexible property names are part of the intended data model rather than an accidental consequence of loosely defined types.
2. String Index Signatures
A string index signature describes the values that can be accessed through string property names. It is commonly used for dictionaries and lookup objects that store values under dynamically selected keys.
type LanguageDictionary = {
[languageCode: string]: string;
};
const translations: LanguageDictionary = {
en: "Welcome",
fr: "Bienvenue",
es: "Bienvenido",
de: "Willkommen"
};
function getTranslation(code: string): string | undefined {
return translations[code];
}
console.log(getTranslation("en"));
console.log(getTranslation("fr"));
console.log(getTranslation("unknown"));
The LanguageDictionary type allows any string key with a string value. This is appropriate when the collection of language codes is not fixed in the type definition.
Notice that getTranslation returns string | undefined. An index signature does not guarantee that every possible key has actually been added to the object. A lookup using an unknown key may return undefined at runtime.
Under strict type-checking settings, the noUncheckedIndexedAccess option can make indexed reads reflect this possibility more consistently, including for dictionaries with index signatures.
String index signatures are useful for translation dictionaries, user-defined labels, runtime configuration, feature flags, and other collections whose property names vary according to application data.
3. Number Index Signatures
TypeScript also supports number index signatures. They describe values accessed using numeric indexes and are particularly useful for specialized array-like structures or numeric lookup objects.
interface ScoreTable {
[index: number]: number;
}
const scores: ScoreTable = {
0: 85,
1: 92,
2: 78
};
scores[3] = 95;
console.log(scores[0]);
console.log(scores[1]);
console.log(scores[3]);
The index signature requires numeric-indexed properties to contain numbers. It allows values to be retrieved or assigned using expressions such as scores[0] and scores[3].
JavaScript object property keys are ultimately strings or symbols, so numeric property access is converted to a corresponding property key. A number index signature describes the numeric access pattern at the TypeScript level; it does not create a special numeric-keyed storage mechanism.
Ordinary arrays are generally preferable when you need a sequence of values with operations such as push, map, and filter. Number index signatures are more appropriate when an object-like lookup structure is intentional.
When a type declares both string and number index signatures, the numeric index signature's value type must be compatible with the string index signature's value type because numeric property access can also be accessed through its string representation.
4. Index Signatures with Multiple Allowed Value Types
Sometimes a dynamic object needs to store several kinds of values. You can express this by using a union type as the index signature's value type.
interface AppSettings {
[key: string]: string | number | boolean;
}
const settings: AppSettings = {
theme: "dark",
retryCount: 3,
notificationsEnabled: true,
language: "English"
};
settings.maxConnections = 10;
console.log(settings.theme);
console.log(settings.retryCount);
console.log(settings.notificationsEnabled);
Every string-keyed property must contain a string, number, or boolean. This makes the object more flexible than a dictionary that accepts only one value type.
The union should reflect the values the object is actually meant to support. If every possible property can have any type, TypeScript loses much of the benefit of static checking and consumers must handle a wider range of values.
When different properties have distinctly different meanings, consider defining explicit properties for known fields and using a narrower dynamic-property rule for additional values.
5. Combining Explicit Properties with an Index Signature
An object type can contain explicitly named properties as well as an index signature. Explicit properties provide clearer names for important fields, while the index signature allows additional properties that follow a shared value type.
interface UserMetadata {
id: number;
name: string;
[key: string]: string | number;
}
const user: UserMetadata = {
id: 101,
name: "Asha",
department: "Engineering",
experience: 3
};
console.log(user.id);
console.log(user.name);
console.log(user.department);
console.log(user.experience);
The interface explicitly declares id and name while permitting additional string-keyed properties whose values are strings or numbers.
A critical rule applies when explicit properties are combined with a string index signature: every explicit property must have a type compatible with the index signature's value type.
interface InvalidMetadata {
[key: string]: string;
name: string;
// Compile-time error:
// age: number;
}
The age property cannot have type number while the string index signature requires every string-keyed property to be a string.
This restriction helps preserve consistent property access. If a field must have an unrelated type, a broader union or a different object design may be required.
6. Readonly Index Signatures
The readonly modifier can be applied to an index signature when properties should not be reassigned through the declared type. This is helpful when a function receives a dictionary that it should inspect without modifying.
interface ReadonlyDictionary {
readonly [key: string]: string;
}
const labels: ReadonlyDictionary = {
home: "Home",
courses: "Courses",
profile: "Profile"
};
console.log(labels.home);
console.log(labels.courses);
// Compile-time error:
// labels.home = "Dashboard";
// Compile-time error:
// labels.settings = "Settings";
The readonly index signature prevents ordinary property assignments through the labels reference. Properties can still be read, and the object can be passed to functions that accept compatible readonly dictionary types.
Like other readonly declarations, this is a compile-time restriction rather than a runtime freeze. JavaScript code or another mutable reference might still modify the underlying object.
Readonly dictionaries are useful for fixed configuration, translation tables, lookup data, and APIs where consumers should access values without modifying the collection through that reference.
7. Index Signatures with Interfaces and Type Aliases
Index signatures can be declared in both interfaces and object type aliases. The syntax and general behavior are the same, so you can select either form according to how the type will be used.
interface StringDictionary {
[key: string]: string;
}
type NumberDictionary = {
[key: string]: number;
};
const translations: StringDictionary = {
hello: "Hello",
goodbye: "Goodbye"
};
const scores: NumberDictionary = {
Asha: 95,
Rahul: 88,
Maya: 91
};
console.log(translations.hello);
console.log(scores.Asha);
StringDictionary allows arbitrary string keys with string values, while NumberDictionary allows arbitrary string keys with number values.
Interfaces are often convenient for contracts that need to be extended or implemented by classes. Type aliases are useful when the dictionary is part of a broader type expression or needs to be composed with other types.
When a dynamic object contains only values associated with keys, both approaches can work well. Keep the definition focused and choose a representation that fits the surrounding type design.
8. Index Signatures vs Record
TypeScript provides the Record utility type as another way to describe objects whose property keys and values follow defined types. Record is often a concise alternative when an object behaves like a dictionary.
type ScoreDictionary = Record;
const scores: ScoreDictionary = {
Asha: 95,
Rahul: 88,
Maya: 91
};
scores.Kiran = 84;
console.log(scores.Asha);
console.log(scores.Kiran);
Record describes an object type with string keys and numeric values. This has a similar practical use to a string index signature that returns numbers.
Record also supports a finite union of keys. For example, Record<"html" | "css", boolean> describes an object with those required keys and boolean values.
type FeatureFlags = Record<"html" | "css", boolean>;
const features: FeatureFlags = {
html: true,
css: false
};
console.log(features.html);
console.log(features.css);
A finite key union is more restrictive than an unrestricted string index signature because it represents a known set of required properties.
Choose an index signature when you want to express the rule directly within an object contract, and choose Record when a mapped object type with specified key and value types communicates the requirement more clearly.
9. Template Literal Pattern Index Signatures
TypeScript supports template literal pattern index signatures, which allow additional property names matching a particular string pattern. This is useful when an object has well-known properties alongside a controlled category of dynamic keys.
interface UserAttributes {
id: number;
name: string;
[key: `data-${string}`]: string;
}
const user: UserAttributes = {
id: 101,
name: "Asha",
"data-theme": "dark",
"data-region": "Asia"
};
console.log(user.id);
console.log(user["data-theme"]);
console.log(user["data-region"]);
The pattern [key: `data-${string}`] permits additional properties whose names begin with data-. This is more restrictive than accepting arbitrary string keys.
The declared id and name properties remain available as explicit fields. Additional fields must match the required prefix pattern and have string values.
Pattern index signatures are useful for data attributes, namespaced metadata, custom property families, and objects where additional keys follow a predictable naming convention.
Use a pattern only when the naming convention is intentional and stable. If properties come from a completely unrestricted set of names, a regular string index signature or Record may be more appropriate.
10. Index Signatures and keyof
The keyof operator produces a type representing the keys of an object type. When an object uses a string index signature, keyof commonly includes string and number because JavaScript permits numeric property access through corresponding string property keys.
interface StringDictionary {
[key: string]: string;
}
type DictionaryKey = keyof StringDictionary;
// string | number
const labels: StringDictionary = {
home: "Home",
courses: "Courses"
};
function getLabel(
dictionary: StringDictionary,
key: string
): string | undefined {
return dictionary[key];
}
console.log(getLabel(labels, "home"));
console.log(getLabel(labels, "profile"));
Because a string index signature permits string keys and numeric property access is compatible with JavaScript's property-key behavior, keyof StringDictionary is string | number.
If you use a finite union of keys instead, keyof can represent that smaller set. For example, keyof { home: string; courses: string } produces the literal union "home" | "courses".
Understanding this difference is useful when building generic dictionary utilities and type-safe property-access functions. It also explains why index signatures provide more flexibility but less precise knowledge about which individual keys actually exist.
11. Common Mistakes with Index Signatures
Using an incompatible explicit property
A declared property covered by a string index signature must have a compatible value type. If the signature allows strings only, an explicitly declared numeric property will cause a type error.
Assuming every dictionary key exists
An index signature describes which values are allowed for keys that are present. It does not guarantee that every possible key has been populated. Handle missing values and consider noUncheckedIndexedAccess.
Using an overly broad value type
If a dictionary accepts any, many useful checks are bypassed. Prefer an accurate value type or a narrow union that describes the supported values.
Using a dictionary for a fixed schema
If the accepted keys are known in advance, an explicit object type or Record with a finite key union can provide stronger guarantees than an unrestricted string index signature.
Confusing readonly with runtime immutability
A readonly index signature prevents ordinary assignment through that typed reference but does not freeze the object or protect every other reference at runtime.
Expecting index signatures to validate external data
TypeScript checks declared types during development. External JSON, API payloads, and untrusted values still need runtime validation when the actual object structure must be guaranteed.
Best Practices for Index Signatures
- Use index signatures when property names genuinely need to be dynamic.
- Choose the narrowest practical value type instead of using any.
- Combine explicit properties with index signatures when important fields deserve named contracts.
- Ensure explicit properties are compatible with the index signature's value type.
- Use Record with finite key unions when only a known set of keys is permitted.
- Consider noUncheckedIndexedAccess when dictionary lookups may return missing values.
- Use readonly index signatures when callers should not assign properties through that reference.
- Use template literal pattern signatures when extra keys must follow a predictable naming convention.
- Keep dynamic dictionaries separate from fixed domain models when combining them would make the type unnecessarily broad.
- Validate external values at runtime when their actual structure or contents cannot be trusted.
Conclusion
TypeScript index signatures allow objects to support dynamic property names while maintaining consistent value types. String and number signatures, readonly declarations, unions, and template literal patterns cover a range of dictionary and metadata use cases.
Start with simple string dictionaries, then practise mixed property structures, readonly signatures, Record, and pattern-based keys. Choose the most precise representation for your data, handle missing lookup results safely, and use runtime validation where necessary. These techniques help create flexible objects without giving up the benefits of TypeScript's static type system.