Home > Back-end >  How i do to access key of nested object in my interface with type generics?
How i do to access key of nested object in my interface with type generics?

Time:07-16

I want to access my nested object key in my interface, but I cannot access that. In my first case, the not nested object are can be access in my parameter function, but nested key is cannot. Could you help me to solve this?

function myFunc<T extends object>(): {
  watch: (type: keyof T) => void
} {
  return { watch: () => {} }
}

interface Props {
  name: string
  age: number
  height: {
    ok: boolean
  }
}

const { watch } = useForm<Props>()
watch('age')

CodePudding user response:

You can look at this post for the possible options - Typescript: deep keyof of a nested object

For your specific example I think you can try the following:

type Join<K extends string, P extends string> = `${K}${"" extends P ? "" : "."}${P}`;

type Paths<T> = T extends object
  ? { [K in keyof T]-?: K extends string
      ? `${K}` | Join<K, Paths<T[K]>> 
      : never
    }[keyof T]
  : never

function useForm<T extends object>(): {
  watch: (key: Paths<T>) => void
} {
  return { watch: () => {} }
}
  • Related