Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
JoshuaKGoldberg opened this issue Aug 14, 2022 · 0 comments
Open

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

JoshuaKGoldberg opened this issue Aug 14, 2022 · 0 comments
Assignees
Labels
type: article Adding a new article .mdx file

Comments

@JoshuaKGoldberg
Copy link
Collaborator

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"
@JoshuaKGoldberg JoshuaKGoldberg added the type: article Adding a new article .mdx file label Aug 14, 2022
@JoshuaKGoldberg JoshuaKGoldberg self-assigned this Aug 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: article Adding a new article .mdx file
Projects
None yet
Development

No branches or pull requests

1 participant