LearningTypeScript / site

Companion website for the Learning TypeScript book.
https://learningtypescript.com
MIT License
48 stars 12 forks source link

Article: Using generics map from object keys to values #81

Open JoshuaKGoldberg opened 2 years ago

JoshuaKGoldberg commented 2 years ago

This is covered in the book, but keeps coming up as something people ask for help with. There's a difference between taking in a keyof typeof type and taking in a type parameter that extends the type.

Example: https://discord.com/channels/508357248330760243/942074070860705852/1008521509532356649

const scratchData = {
  apple: "fruit",
  beet: "vegetable",
} as const;

function getDataFixed(key: keyof typeof scratchData) {
  return scratchData[key];
}

const fromApple = getDataFixed("apple");
//    ^? "fruit" | "vegetable"

function getDataGeneric<Key extends keyof typeof scratchData>(key: Key) {
  return scratchData[key];
}

const fromAppleGeneric = getDataGeneric("apple");
//    ^? "fruit"