DEV Community

Discussion on: Indexing objects in TypeScript

Collapse
 
mapleleaf profile image
MapleLeaf • Edited

Turns out TS 3.0 broke this 🙃

I'm not quite sure how to fix it at the moment, but if someone else has a solution, I'm all ears. I know Lodash's types are pretty comprehensive, so I might start looking there myself

EDIT: I love it when I figure it out right after posting the comment. It needs to be string | number | symbol, since 3.0 expanded the kinds of types that can be used for object keys. We can shorten that to keyof any.

function hasKey<O>(obj: O, key: keyof any): key is keyof O {
  return key in obj
}

Updated the blog post. Thanks for the heads up 🙌

Collapse
 
newswim profile image
Dan Minshew • Edited

Nice! I ended up opting for the union type, just because any gives me anxiety . .

function hasKey<O>(obj: O, key: string | number | symbol): key is keyof O {
  return key in obj
}
Thread Thread
 
mapleleaf profile image
MapleLeaf

👍 Might even be more readable that way.