TypeScript Tutorial: How to retrieve the data type of a deeply nested object

I have a question about extracting the type of a nested object with similar structures. The object in question contains multiple sub-objects that all follow the same pattern.

const VALUES = {
    currentStreak: {
      display: "Current streak",
      value: currentStreak,
    },
    longestStreak: {
      display: "Longest streak",
      value: longestStreak,
    },
    contributionsThisYear: {
      display: "Contributions this year",
      value: contributionsThisYear,
    },
    totalContributions: {
      display: "Total contributions",
      value: totalContributions,
    },
    currentCompany: {
      display: "Working at",
      value: currentCompany,
    },
}

The main keys of the object are working fine, but I'm looking to define types for the individual keys within each object as well.

export type Something = {
  [key in keyof typeof VALUES]: { [key: string]: string | number };
};

How can I properly define the types for each object so that they contain both display and value, where value can be either a string or a number?

Apologies if this is repetitive! I just want to get a clear understanding once and for all.

Answer №1

If Something is meant to represent the type for VALUES, then there is an issue because you are referring to the object you want to type in its own type declaration.

Unless you have an Enum with string values to derive the keys from, it is recommended to type the keys simply as strings:

interface innerSomething {
  display: string
  value: number | string
}

type Something = {
  [key in string]: innerSomething
}

If using an Enum, the syntax should be similar to this:

enum SomethingKeys {
    currentStreak,
    longestStreak,
    contributionsThisYear,
    totalContributions,
    currentCompany
}

interface innerSomething {
  display: string
  value: number | string
}

type Something = {
  [key in keyof typeof SomethingKeys]: innerSomething;
}

Alternatively, instead of declaring an interface, you can define the type of the inner objects within the actual Something declaration like so:

enum SomethingKeys {
    currentStreak,
    longestStreak,
    contributionsThisYear,
    totalContributions,
    currentCompany
}

type Something = {
  [key in keyof typeof SomethingKeys]: { display: string, value: number | string };
}

However, utilizing an interface tends to be more readable and easier to maintain.

Answer №2

Defining the following section is a key step

const ItemData = {
  title: string;
  price: number;
};

export const ItemList = {
  [key in keyof typeof PRODUCTS]: ItemData;
};

Answer №3

console.log(typeof VALUES[keyof typeof VALUES]);

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

Can you share the appropriate tsconfig.json configuration for a service worker implementation?

Simply put: TypeScript's lib: ['DOM'] does not incorporate Service Worker types, despite @types/service_worker_api indicating otherwise. I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck at t ...

How can I create interfaces for deeply nested objects in TypeScript?

Check out my current JSON data below: { "state_1": { "date": [ { 1000: { "size": 3, "count": 0 } }, { 1001: { "size" ...

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

Navigating through unorganized items in Angular 9

Exploring Object Structures As I navigate through a complex object, I aim to extract all values within the ngbtypeahead. However, the challenge lies in the fact that the keys within this object are distinct, hindering my ability to retrieve these values ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Visual Studio is refusing to highlight my code properly, intellisense is failing to provide suggestions, and essential functions like go to definition are not functioning as expected

Due to a non-disclosure agreement, I am unable to share any code. However, I am experiencing an issue with Visual Studio not highlighting my code or allowing me to utilize its built-in tools. While I can rebuild the project, I cannot edit or access any fil ...

How come the information I receive when I subscribe always seems to mysteriously disappear afterwards?

I've been working on a web project using Angular, and I've run into an issue with my code that's been causing problems for a while now. The problem lies in fetching data from a server that contains translations: getTranslations(): Observab ...

Replace the default Material UI 5.0 typography theme with custom fonts on a global scale

My current challenge involves incorporating two personal fonts into the Material UI 5.0. My goal is to apply these fonts globally by overriding the theme settings. However, I have encountered issues with loading the fonts properly and modifying the typogra ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Angular8 does not recognize custom paths that have been added to the tsConfig file

Hey there! I'm facing an issue with Angular not recognizing a custom path I added to my tsConfig file. It seems like Angular already has a baseUrl property set to ./, starting from the current folder where the tsConfig file is located. The code snippe ...

Using TypeScript to create a generic type that wraps around HTMLElements

I attempted to execute this action, however the assignment to this.element is not working and I am unsure why. class Elem<T> { public element : T; constructor(typeElement:string){ this.element = document.createElement(typeElement); ...

Creating autorest client based on various OpenAPI versions

I'm currently exploring options for creating a Typescript client from our .NET API. After researching various tools, I decided to go with Autorest, as it is Node-based and fits my skillset. While I am aware of Swashbuckle, my knowledge leans more towa ...

I am encountering an issue where the nested loop in Angular TypeScript is failing to return

I am facing an issue with my nested loop inside a function. The problem is that it is only returning the default value of false, instead of the value calculated within the loop. Can someone please point out what I might be doing incorrectly? Provided belo ...

Efficiently managing repeated records in NodeJS using loops

I am trying to retrieve sales records for specific products from a table in my database based on client ID. This is how I attempted to achieve it: public async getData(clientID: any): Promise<any> { try { return await client .scan( ...