What is the best approach to retrieve the key of a nested object within my interface using type generics?

I'm facing an issue with accessing a nested object key in my interface. In my scenario, I am able to access non-nested object keys in my parameter function, but the nested key seems inaccessible. Can anyone provide assistance on how to resolve this issue?

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')

Answer №1

Refer to this post for a list of possible solutions - Typescript: retrieving nested object keys

If you're looking for a solution tailored to your specific example, consider giving this a try:

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

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

function createForm<T extends object>(): {
  observe: (key: ObjectPaths<T>) => void
} {
  return { observe: () => {} }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing TypeScript to throw errors regarding the initialState type when defining redux slices with createSlice in reduxToolkit, despite it being the correct type specified?

Here is my implementation of the createSlice() function: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; type TransferDeckModeType = "pipetting" | "evaluation" | "editing"; var initialState: Transfer ...

What is the process for developing a bespoke TypeScript Declaration library and integrating it into my projects through NPM or GitHub Packages?

Project Description I am currently developing a customized TypeScript type declaration library that will be utilized in various projects. However, I am encountering an issue when it comes to importing this TypeScript library into my projects. Although it ...

What is the process for integrating custom TypeScript declaration files into the final build with rollup.js?

I am working on a project in Typescript where the files are built using rollup.js. Within my project, I have certain declaration files set up and I am curious if it is feasible to include these declaration files in the final built declaration file. Declar ...

Sequelize: Issue with duplicate $ in JSON_EXTRACT function

Can anyone help me with an issue I'm facing when using double dollar in a query with JSON_EXTRACT? Here is my query: const user = await UserModel.findOne({ where: where(fn('JSON_EXTRACT', col('config'), '$.type'), ty ...

How can one retrieve a specific type? The combination of T[keyof T] unifies all types into one

const obj = { role : 'admin', user : { id : 1, name : 'vasa', }, } const fun = <T>(obj: T): Record<`set${Capitalize<string & keyof T>}`, (a : T[keyof T]) => void> ...

Retrieve a multitude of nested Records within the returnType that correlate with the number of arguments provided to the function

My goal is to dynamically define a deeply nested ReturnType for a function based on the number of arguments passed in the "rest" parameter. For example, if we have: getFormattedDates( dates: Date[], ...rest: string[] // ['AAA', 'BBB&apos ...

What is the best way to set a value for a variable that is asynchronous by design?

I'm currently working on an Appium automation framework that is typescript based. The element locator strategy used in this framework is async due to the nature of the plugin I am using, which requires the use of await. However, I encountered some err ...

The Unit Test for Angular NgRx is not passing as expected

I'm facing difficulties with my unit tests failing. How can I verify that my asynchronous condition is met after a store dispatch? There are 3 specific checks I want to perform: 1/ Ensure that my component is truthy after the dispatch (when the cond ...

encountering issues with configuring TypeScript LSP in NeoVim with the use of the lazy package manager

Encountered an error in nvim when opening a .ts file. Using mason, mason-lspconfig, and nvim-lspconfig for lsp setup. Lua language lsp is functioning properly, but facing errors with ts files as shown in the screenshot below: https://i.stack.imgur.com/gYM ...

Utilizing Flux Container.create with Typescript 2.8: A Comprehensive Guide

I need to upgrade my TypeScript version from 2.2 to 2.8 in a React/Flux project. Below is the code snippet defining a store using the container.create utility function: import * as React from 'react'; import { Container } from 'flux/utils& ...

Can you use the useCallback function within a nested callback function?

within component A: const retrieveOnClick = useCallback( (rec: GenericRec): (() => void) => () => { setSelectedRecord(rec); }, [], ); inside component B which is a child of A: const displayRecord = useCallback( (row: Row& ...

Can someone provide guidance on utilizing the map function to iterate through intricate components in TypeScript?

I am facing a challenge while trying to iterate through a complex object containing 'inner objects'. When using the map function, I can only access one level below. How can I utilize map and TypeScript to loop through multiple levels below? Whene ...

Encountering a node module issue when implementing graphql in a TypeScript project

I encountered issues when attempting to utilize the @types/graphql package alongside TypeScript Node Starter node_modules//subscription/subscribe.d.ts(17,4): error TS2314: Generic type AsyncIterator<T, E>' requires 2 type argument(s). node_modu ...

Angular TextInput Components don't seem to function properly when dealing with arrays

I am trying to create a collection of text input components with values stored in an array. However, when using the following code, the values seem to be placed incorrectly in the array and I cannot identify the bug. <table> <tr *ngFor="let opt ...

Steps for incorporating jQuery files into Angular 4

As a beginner in Angular 4, I am faced with the challenge of calling a jQuery function using an HTML tag from a method. The jQuery method is located in a separate file. How can I incorporate this into my Angular project? Here's an example: sample() { ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

Calculating Events with the onChange Method in Typescript

How do I calculate the total ticket price when I adjust the number of individuals? HTML Code : <div class="row"> <div class="col-md-6"> <label for="person">Person</label> <div class="form-group"> ...

Creating a map object in Typescript with limited enumerable properties

Is there a way to restrict the values of an object map to a certain type while still being able to enumerate its keys? Consider the following: const obj = { a: 'a', b: 'b' } type Obj = typeof obj const obj2: Obj In this case, o ...

Warning: The use of the outdated folder mapping "./" in the "exports" field for module resolution in the package located at node_modulespostcsspackage.json is deprecated

I recently upgraded my Node to version 16 and since then I have been encountering this issue while building my Angular app. Warning: The folder mapping "./" used in the "exports" field of the package located at ".../node_modules/postcss/package.json" is de ...

User interface designed for objects containing multiple keys of the same data type along with a distinct key

I have a question that relates to this topic: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?. My goal is to define an interface for an object that can have multiple optional keys, all of t ...