Skip to content

Mapped types

Daisho Komiyama edited this page Nov 1, 2022 · 5 revisions
type Fruit = {
  name: string
  color: string
  mass: number
}
 
// mapped type
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'.
}
Clone this wiki locally