Skip to content

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

@JoshuaKGoldberg

Description

@JoshuaKGoldberg

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"

Metadata

Metadata

Labels

type: articleAdding a new article .mdx file

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions