Index Signatures in TypeScript
Index Signatures in TypeScript
Section titled “Index Signatures in TypeScript”Basic Index Signature
Section titled “Basic Index Signature”// String index signatureinterface StringDict { [key: string]: string;}
const translations: StringDict = { hello: "Hola", goodbye: "Adiós",};Number Index Signature
Section titled “Number Index Signature”interface NumberDict { [index: number]: string;}
const arr: NumberDict = ["a", "b", "c"];console.log(arr[0]); // "a"Mixed Signatures
Section titled “Mixed Signatures”interface MixedDict { [index: string]: number | string; length: number; // OK: number is in the union name: string; // OK: string is in the union}Readonly Index Signature
Section titled “Readonly Index Signature”interface ReadonlyDict { readonly [key: string]: number;}
const scores: ReadonlyDict = { alice: 95, bob: 87 };// scores.alice = 100; // ❌ Error: Index signature is readonlyReal Project Example
Section titled “Real Project Example”// Form errors dictionaryinterface FormErrors { [field: string]: string | undefined;}
// API headersinterface Headers { [header: string]: string | string[] | undefined; "Content-Type": string; Authorization?: string;}Interview Questions
Section titled “Interview Questions”Easy: What does [key: string]: string mean?
Medium: What are the restrictions on index signature parameter types?
Hard: How would you type a dictionary that maps string keys to specific value types?