Use for questions on index signatures, a feature of TypeScript that allows for object types with unknown properties (both numeric and string signatures are supported) to be restricted to certain types. Always use with the [typescript] language tag. Do not use it for questions that merely involve index signatures.
About
Index Signatures allow object types in TypeScript to have unknown properties that are restricted to certain types. Signatures can be either numeric or string-based, and both can be present at the same time (with a small caveat). The presence of an index signature also restricts known properties to be of the same type unless they are extracted in another object type and combined with the index signature via a union type.
type StringIndexed = { [key:string]: boolean; };
const validSI: StringIndexed = { isStringBased: true }; // Ok
const invalidSI: StringIndexed = { answer: 42 }; // Type 'number' is not assignable to type 'boolean'
type NumberIndexed = { [index:number]: string; };
const validNI: NumberIndexed = ["one", "two"];
const invalidNI: NumberIndexed = [1,2]; // Type 'number' is not assignable to type 'string'
type BothIndexed = {
[key:string]: boolean|string; // Needs to be a union because A[0] is the same as A["0"]
[index:number]: string;
};
const validBoth:BothIndexed = {
acceptsBoth: true, // Ok
thisIsAlsoOkThough: "anything", // a trade-off for combining signatures
42: "answer" // Ok
}
type WithKnownProperties = {
[prop: string]: string;
} | { answer: 42; };
const known: WithKnownProperties = {
answer: 42, // Ok
question: "unknown" // Ok
}
Usage Guidance
Use for questions about index signatures, their usage rules and caveats, not for questions simply involving them.
Always use with the typescript language tag.