Skip to content

Mapped types

Daisho Komiyama edited this page Jun 19, 2023 · 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 }

Another example;

type Hero = {
    title: string
}

type Overview = {
    intro: string,
    description: string
}
 
type MyRecord = { [k in "hero"]: Hero } | { [k in "overview"]: Overview }
 

function printComponent(comp: MyRecord) {
    const result = comp
    console.log('==>', result)
}

const hero = {
    hero: {
        title: 'Hedo'
    }
}

const overview = {
    overview: {
        intro: 'Introduction',
        description: 'Desc'
    }
}

printComponent(hero)
printComponent(overview)

// mapped type (generic)
type MyGenericRecord<KeyType, ValueType> = { [Key in KeyType]: ValueType }
Clone this wiki locally