Retrieving a data type from the key values of deeply nested objects

I'm currently working with JSON data that contains nested objects, and my goal is to extract the unique set of second-level keys as a type. For instance:

const json = {
    'alice': {
        'dogs': 1,
        'birds': 4,
    },
    'bob': {
        'dogs': 2,
        'cats': 5,
    },
}

type animals1 = keyof typeof json['alice'] | keyof typeof json['bob']
// animas1 = 'dogs' | 'birds' | 'cats'

type animals2 = keyof typeof json['alice' | 'bob']
// animals2 = 'dogs'

type people = keyof typeof json
type animals3 = keyof typeof json[people]
// animals3 = 'dogs'

My objective is to retrieve 'dogs' | 'birds' | 'cats' (like in animals1) without explicitly stating the first-level keys. However, it seems like the approach I'm using (animals3) returns only the common keys rather than the union.

Is there a way to achieve this desired outcome?

Answer №1

To generate a union of the keys at the second level, you can iterate over the keys of T and then flatten them using [keyof T]:

type UnionOfSecondLevelKeys<T> = {
  [K in keyof T]: keyof T[K]
}[keyof T];

const data = {
  'alice': {
    'dogs': 1,
    'birds': 4,
  },
  'bob': {
    'dogs': 2,
    'cats': 5,
  },
};

type animals = UnionOfSecondLevelKeys<typeof data>;
// animals = "dogs" | "birds" | "cats"

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

Incorporating a filtering search bar in Ionic React to efficiently sort pre-existing lists based on their titles

Struggling to implement a search bar in my Ionic application has been quite challenging. I've searched for examples and tutorials, but most of them are based on Angular with Ionic. The React example in the Ionic docs didn't provide much help eith ...

Choose an option from a selection and showcase it

I need to implement a modal that displays a list of different sounds for the user to choose from. Once they select a sound, it should be displayed on the main page. Here is the code snippet for the modal page: <ion-content text-center> <ion-ca ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular. In this project, I am attempting to divide the form into two sections: Person Name and Personal Details. While I have successfully grouped fields for P ...

Why is it that when I try to create a table using the "Create Table" statement, I keep getting an error saying "Near '(': syntax error"?

Error : There seems to be a syntax error near "(". Here is the SQL statement causing the issue: CREATE TABLE IF NOT EXISTS tickets ( numero INTEGER PRIMARY KEY AUTOINCREMENT, identifier VARCHAR(4) NOT NULL, subject VARCHAR(150) NOT NULL, ...

Ways to adjust height dynamically to auto in React

I am currently stuck on a problem concerning the adjustment of my listing's height dynamically from 300 to auto. My goal is to create a post-like feature where users can click "read more" to expand and view the full post without collapsing it complete ...

What is preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

Creating a personalized design for MUI TextField spin button

Looking to customize the appearance of the up/down spin buttons in MUI TextField. Desiring white arrows and a black surrounding area that's slightly larger, akin to this: I'm aware that adjustments need to be made within input::-webkit-outer-sp ...

In React-Native, implement a function that updates one state based on changes in another state

I need to trigger a function when a specific state changes. However, I encountered the error 'maximum update depth reached'. This seems illogical as the function should only respond to changes from stateA to update stateB. I attempted using setSt ...

Transferring data types to a component and then sending it to a factory

I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error: error TS1005: ',' expected. The issue arises when I try to pa ...

Error Encountered during Compilation of React TypesIs this okay

Currently, I am working on an MVC project that involves the use of TypeScript. To access the types required for this project, I have also integrated React. To obtain the React types, I performed an npm install --save-dev @types/react (similarly for react-d ...

Altering the dimensions of radio buttons

I am a newcomer to using material-ui. I am currently working on incorporating radio buttons in a component and would like to reduce its size. While inspecting it in Chrome, I was able to adjust the width of the svg icon (1em). However, I am unsure how to a ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

Creating an interface for writing types in Firebase functions/storage/database

What are the TypeScript types for Firebase functions, storage, and admin? I'm fairly new to TypeScript and currently in the process of updating my JavaScript code to TypeScript. Within my code, I am generating a context object. const context = { ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

Leveraging an intersection type that encompasses a portion of the union

Question: I am currently facing an issue with my function prop that accepts a parameter of type TypeA | TypeB. The problem arises when I try to pass in a function that takes a parameter of type Type C & Type D, where the intersection should include al ...

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

What is the best way to implement custom sorting for API response data in a mat-table?

I have been experimenting with implementing custom sorting in a mat-table using API response data. Unfortunately, I have not been able to achieve the desired result. Take a look at my Stackblitz Demo I attempted to implement custom sorting by following t ...