I carry this file with me wherever I go
export interface StringTMap<T> { [key: string]: T; }; export interface NumberTMap<T> { [key: number]: T; }; export interface StringAnyMap extends StringTMap<any> {}; export interface NumberAnyMap extends NumberTMap<any> {}; export interface StringStringMap extends StringTMap<string> {}; export interface NumberStringMap extends NumberTMap<string> {}; export interface StringNumberMap extends StringTMap<number> {}; export interface NumberNumberMap extends NumberTMap<number> {}; export interface StringBooleanMap extends StringTMap<boolean> {}; export interface NumberBooleanMap extends NumberTMap<boolean> {};
StringTMap and NumberTMap are generic and can be used to create maps of any type (via let myTypeMap: StringTMap<MyType> = {} ). The rest are useful predefined mappings between generic literal types.
The important syntax here is { [key: string]: T; } { [key: string]: T; } , which indicates that the interface uses an object literal with keys of type string (the word key can be any identifier and should be used to indicate the importance of the key) and enter T values. If you want to create an object with string "names" for keys and boolean values (and not use the inheritance described above), its interface will be { [name: string]: boolean } .
You can use the same syntax to ensure that the object has a key for each record in the join type:
type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday"; type ChoresMap = { [day in DayOfTheWeek]: string }; const chores: ChoresMap = { // ERROR! Property 'saturday' is missing in type '...' "sunday": "do the dishes", "monday": "walk the dog", "tuesday": "water the plants", "wednesday": "take out the trash", "thursday": "clean your room", "friday": "mow the lawn", };
Of course, you can also make this a universal type!
type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday"; type DayOfTheWeekMap<T> = { [day in DayOfTheWeek]: T }; const chores: DayOfTheWeekMap<string> = { "sunday": "do the dishes", "monday": "walk the dog", "tuesday": "water the plants", "wednesday": "take out the trash", "thursday": "clean your room", "friday": "mow the lawn", "saturday": "relax", }; const workDays: DayOfTheWeekMap<boolean> = { "sunday": false, "monday": true, "tuesday": true, "wednesday": true, "thursday": true, "friday": true, "saturday": false, }
10/10/2018 update: See @dracstaxi's answer below - now there is a built-in Record type that does this for you.