-
Notifications
You must be signed in to change notification settings - Fork 0
Mapped types
Daisho Komiyama edited this page Nov 1, 2022
·
5 revisions
type Fruit = {
name: string
color: string
mass: number
}
// mapped type (very specifically operates)
type MyRecord = { [FruitKey in "apple" | "cherry"]: Fruit } // or simply { [k in "apple" | "cherry"]: Fruit }
function printFruitCatalog(fruitCatalog: MyRecord) {
const cherry = fruitCatalog.cherry
const apple = fruitCatalog.apple
// ^ const apple: Fruit
const pineapple = fruitCatalog.pineapple
// ^ TSC Error: Property 'pineapple' does not exist on type 'MyRecord'.
}
// mapped type (generic)
type MyGenericRecord<KeyType, ValueType> = { [Key in KeyType]: ValueType }