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'.
};
Aqui, a interface AgeMap
impõe chaves como seqüências de caracteres e valores como números. A palavra-chave name
pode ser qualquer identificador e deve ser usada para sugerir a sintaxe da sua interface / tipo.
Você pode usar uma sintaxe semelhante para impor que um objeto tenha uma chave para cada entrada em um tipo de união:
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",
};
Obviamente, você também pode fazer deste um tipo genérico!
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,
};
Atualização 10.10.2018:
Confira a resposta de @ dracstaxi abaixo - agora há um tipo interno Record
que faz a maior parte disso para você.
Atualização 1.2.2020:
removi completamente as interfaces de mapeamento pré-fabricadas da minha resposta. A resposta de @ dracstaxi os torna totalmente irrelevantes. Se você ainda deseja usá-los, verifique o histórico de edições.