DEV Community

loading...

Discussion on: Indexing objects in TypeScript

Collapse
newswim profile image
Dan Minshew

I get a kind of interesting error when using hasKey,

A type predicate's type must be assignable to its parameter's type.
  Type 'keyof O' is not assignable to type 'string'.
    Type 'string | number | symbol' is not assignable to type 'string'.
      Type 'number' is not assignable to type 'string'.

Any idea what's causing this?

Collapse
mapleleaf profile image
MapleLeaf Author • 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 Author

👍 Might even be more readable that way.