#Write a generic that resolve the type matching a nested key within an interface

9 messages · Page 1 of 1 (latest)

edgy ravineBOT
#
ChronicStone#1283

Preview:```ts
// ###############################################
// THE PROBLEM I WANT TO SOLVE
// ###############################################

type Column<Entity extends GenericObject, Key = NestedPaths<DeepRequired<Entity>>> = {
key: Key,
render: (value: PickTypeFromPath<Entity, Key>) => any
...```

old lance
#

i think this type would do what you want:

type PickTypeFromPath<Type, Key> =
  Key extends `${infer Head extends Interpolatable & keyof Type}.${infer Tail}` ? PickTypeFromPath<Type[Head], Tail>
  : Key extends keyof Type ? Type[Key]
  : never
#

but that's not going to be enough to implement this. you'll need some way to allow inferring a different Key for each column in the array. currently your types are saying they are all the same: NestedPaths<DeepRequired<User>> (any key path in User)

red cradle
#

@old lance thanks for the answer. I actually came up with something really close to that when experimenting, but it's as you said, no matter what key I provide I'll get an union type of all available keys ...

#

I don't understand enough typescript to understand why I get this kind of behavior in the context of my implementation, whereas using the type as a standalone works

#

It's like the actual value of the key isn't inferred properly

#

Even though NestedPath outputs correctly

#

From your explanation, what I understand is that NestedPaths points to any key of the object, and I need to narrow it down somehow to the actual key I'm targeting for this to work ?

#

I've unfortunately no idea how to do that