I'm trying to create a type based on an array of objects using one of the recurring (and required) keys, but typescript doesn't handle Array.map() the way I expect:
const list = [
{
_id: 'foo1'
},
{ _id: 'foo2' }
] as const
const listIds = list.map(listValue => listValue._id)
I expect listIds to be inferred as ['foo1', 'foo2'] but is instead treated as ("foo1" | "foo2")[]. This doesn't make sense to me since it's impossible for Array.map to return an array of a different size than the original array.
Is there another way to get the results I'm looking for?
PS. See TypeScript Playground sample here.
For this specific case of getting the value of a specific key, a helper function can be used:
Playground link
However, I don't think there's a simple way of generalising this for any kind of function.
What we really want:
However, this doesn't compile as TypeScript lacks higher-kinded types. There are various hacks for emulating this in TypeScript, but they're cumbersome to use and I don't personally think it's worth it for this problem.