interface AgeMap {
[name: string]: number
}
const friendsAges: AgeMap = {
"Sandy": 34,
"Joe": 28,
"Sarah": 30,
"Michelle": "fifty", // ERROR! Type 'string' is not assignable to type 'number'.
};
Here, the interface AgeMap
enforces keys as strings, and values as numbers. The keyword name
can be any identifier and should be used to suggest the syntax of your interface/type.
You can use a similar syntax to enforce that an object has a key for every entry in a union 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",
};
You can, of course, make this a generic type as well!
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,
};
Finally, you can use the indexing identifier as a type in your indexed type:
type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday";
const weekdayMeta: { [DAY in DayOfTheWeek]: { day: DAY; score: number } } = {
sunday: { day: "sunday", score: 3 },
monday: { day: "monday", score: 4 },
tuesday: { day: "tuesday", score: 2 },
wednesday: { day: "wednesday", score: 0 },
thursday: { day: "thursday", score: 5 },
friday: { day: "friday", score: 6 },
saturday: { day: "sunday", score: 1 }, // ERROR: Type '"sunday"' is not assignable to type '"saturday"'.
};
10.10.2018 update:
Check out @dracstaxi's answer below - there's now a built-in type Record
which does some of this for you.
1.2.2020 update:
I've entirely removed the pre-made mapping interfaces from my answer. @dracstaxi's answer makes them totally irrelevant. If you'd still like to use them, check the edit history.