#Trouble with Records

11 messages · Page 1 of 1 (latest)

covert valley
covert valley
covert valley
#

I figured out how to get it to work using a generic, but I'm not sure why one works over the other.

const simpleMap = {
  item1: {
    common: 1,
  },
  item2: {
    common: 1,
    custom: 1,
  },
}

// Works
function getItem<K extends keyof typeof simpleMap>(key: K) {
  return simpleMap[key];
}

// Doesn't Work
function getItemDoesntWork(key: keyof typeof simpleMap) {
  return simpleMap[key];
}
#

If anyone has any input, I'd love to learn!

outer surge
#

when you say it "doesn't work", you mean the fact that it returns a union type rather than the specific type that goes with the specific key you pass?

#

if so, this is the whole reason generics exist. keyof typeof simpleMap is just 'item1' | 'item2', which is not the same as a type parameter which extends 'item1' | 'item2'

#

!hb generics

jovial fractalBOT
outer surge
#

☝️ maybe that will help

#

K extends keyof typeof simpleMap is a specific type that will be determined at call time. it can be 'item1', 'item2', 'item1' | 'item2', etc depending on what the caller does. OTOH keyof typeof simpleMap is always the unspecific 'item1' | 'item2'

covert valley
#

Yea, after going down the rabbit trail, I realized that keyof just comes back as a string union type, and I use generics all the time. I was just a little lost on why the result of keyof couldn't be used as an index without being lossy.