Dictionary-shaped data
A configuration or lookup object has arbitrary string names but one predictable value type.
TypeScript · Function
Index signatures describe values for properties whose names are not known ahead of time. They support dictionary-like objects while enforcing the declared value type for compatible keys and named properties.
An index signature describes the value type available through dynamic property access when property names are not known in advance. Its parameter uses an allowed key type such as string, number, symbol, or a template-string pattern; named properties in the same object must remain compatible with the applicable index signature.
interface Type {
[key: string]: Value;
}| Name | Type | Description |
|---|---|---|
index | string | number | symbol | template string pattern | The key used for indexed access; it must be a supported index-signature key type. |
The value type specified by the index signature when the object is indexed with a compatible key.
readonly to prevent writes through the indexed access.interface UserFlags {
[username: string]: boolean;
admin: boolean;
}
const flags: UserFlags = { admin: true, alice: false };
const isAdmin = flags["admin"];
const isAlice = flags["alice"];The index signature permits arbitrary string-named flags, while the declared admin property must also be boolean.
A configuration or lookup object has arbitrary string names but one predictable value type.
An array-like abstraction should return a consistent value for numeric access.
Only properties with a known naming convention should be accepted.
An index signature describes the type returned when an object is accessed with a dynamic key. For example, [index: number]: string means numeric indexing produces strings.
Follow-up: How would you restrict keys to a naming pattern? Use a template string pattern index signature, such as [key: data-${string}]: string.
The supported key forms include string, number, symbol, template string patterns, and unions made only from those infinite-domain primitive forms. A union index signature is treated as multiple compatible index signatures.
Follow-up: Why can’t an arbitrary object type be used as the parameter? Index-signature key types are restricted to the documented key forms so the compiler can model property lookup consistently.
A string index signature is broad enough to cover named properties, so each explicitly declared property must have a compatible value type. If numeric and string indexers coexist, the numeric result must be a subtype of the string result.
Follow-up: What happens with keyof on a string-indexed type? It includes string | number, because JavaScript permits numeric property access that is coerced to strings.
keyofindexed access typesnoUncheckedIndexedAccessnoPropertyAccessFromIndexSignaturetemplate string pattern index signatures