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'.
};
Qui, l'interfaccia AgeMap
impone chiavi come stringhe e valori come numeri. La parola chiave name
può essere qualsiasi identificatore e deve essere utilizzata per suggerire la sintassi della tua interfaccia / tipo.
È possibile utilizzare una sintassi simile per imporre che un oggetto abbia una chiave per ogni voce in un tipo di unione:
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",
};
Naturalmente puoi anche rendere questo un tipo generico!
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,
};
Aggiornamento del 10.10.2018:
dai un'occhiata alla risposta di @ dracstaxi qui sotto: ora c'è un tipo integrato Record
che fa la maggior parte di questo per te.
Aggiornamento 1.2.2020:
ho completamente rimosso le interfacce di mappatura pre-create dalla mia risposta. La risposta di @ dracstaxi li rende totalmente irrilevanti. Se desideri comunque usarli, controlla la cronologia delle modifiche.