1

I have an object that is types as PType and looks like this:

import { path } from 'ramda';


const obj: PType = {
  prop1: {
    val1: "foo",
  },
  prop2: {
    foo: "bar",
  }
}

Now, I also created a function to get specific values from the object like so:

export const getProps = (keys: [keyof PType, string]) => path(['obj', ...keys]

And I am using it as such:

export const prop1 = (value: keyof PType['prop1']) => getProps(['prop1', `${value}`]);

So the idea is that value in the prop1 function is types as keyof PType['prop1'] but types as string inside the getProps function.

I tried to fix the string typing by using:

export const getProps = (keys: [keyof PType, keyof PType[keyof PType]) => {...}

but that will not work and TS will not let me do that.

I'd love to pass in a dynamic type there instead of having just a string definition on that place.

I assume there's something like a generic type definition or map but I haven't found a solution for it yet.

wasddd_
  • 937
  • 2
  • 10
  • 19
  • How do you want to call your function ?Could you please provide a link to TS playground with some comments? See [this](https://stackoverflow.com/questions/69126879/typescript-deep-keyof-of-a-nested-object-with-related-type#answer-69129328) is this something that you want? – captain-yossarian from Ukraine Dec 15 '21 at 12:53
  • @captain-yossarian pls find the [ts playground here](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzAQxgCwL5wGZQiOAIimRABNlCAoKgUwA9JY4YBPMWuAeQCMArACrtOAXhbCI2OBH4BuGgGMIAOwDO8GXzhiEVOHDB4wARgBciPfpwQI5wj2RRCAGkv7WtogBsILyxld9QwgwACZzXSs4Byg7bBtqfQwqDHk6Rmh4JTV4AHNaGF4tEUsACgBrWlZVcwBtSo8pIqEOZzh1KGBlXIBdAEptAD4DVDRS2oByTQm2gDp5htV+tPSmLJV1AyMANWQvAFdROFLgsAA5UlpzBslufhbaSdPjCf6huHzC-nGJ55m4AAGABIkEYLiBaBgAcs4AB6WFbELgzjAVRwNC0KCcG5Ne7CJ5GF49No8fbwAEdLq5AHSZRwLxdTjGABsszgAAkIAB3OBciD7LxkOAASTgZFYylIwAUey8rHEHBYGPatGyQuAMFoBC6Ss4jhI8viUEBnyKNK66loyCFt32qipgMp3QBAH4gA) – wasddd_ Dec 15 '21 at 16:52
  • 1
    Updating to function signature to be this: `export const getObj = (keys: [T, keyof ObjType[T]]) => path(['obj', ...keys as (string[])]);` does work, although it isn't so nice to do implicit type casting on the `keys`. You can then call is as `export const propValue = (propName: keyof ObjType['prop1']) => getObj(['prop1', propName]);` which strictly types the `propName`. – Arno van Liere Dec 15 '21 at 20:01
  • @wasddd_ See [this](https://tsplay.dev/N7KerN) example – captain-yossarian from Ukraine Dec 16 '21 at 08:18

0 Answers0