TypeScript: Defining a custom type based on values within a nested object

I'm attempting to generate a unique type from the value of a nested object, but encountering failure if the key is not present on any level of nesting. Can someone point out where I might be making a mistake?


const events = [
  { name: 'foo' },
  { name: 'bar' },
  { value: 'baz' }
] as const;


type Events = typeof events;

type AllValuesOf<T> = T extends any ? T[keyof T] : never;

// Error: Property 'name' does not exist on the type 
type Name = AllValuesOf<Events>['name'] // ideally I want this to be 'foo' | 'bar'

Expected

type Name = "foo" | "bar"

Ts Playground link

Answer №1

It seems like you are interested in creating a type called AllEvents based on certain criteria programmatically:

type AllEvents = {
    name: "foo" | "bar";
    value: "baz";
}

This type would allow you to easily access the union types within it using keys like "name" and "value".

To achieve this, we can start with a union type T of object types (expected to be Events[number], which is the union of elements from events). We first identify all the keys in this union by distributing the keyof operator over unions in T:

type AllKeys<T> = T extends unknown ? keyof T : never;

Next, we combine these keys into a single object type. For each key K in AllKeys<T>, we filter the union T to extract values associated with that key. This can be achieved using distributive conditional types and the infer keyword for extraction:

type Combine<T> = 
  { [K in AllKeys<T>]: T extends Record<K, infer V> ? V : never };

By combining these steps, we arrive at the final AllEvents type as desired:

type AllEvents = Combine<Events[number]>;
/* type AllEvents = {
    name: "foo" | "bar";
    value: "baz";
} */

You can now access specific types within this structure by indexing as needed:

type Name = AllEvents['name'];
//type Name = "foo" | "bar"

Link to Playground with Code Example

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

Should the PHP interface be exported to a Typescript interface, or should it be vice versa?

As I delve into Typescript, I find myself coding backend in PHP for my current contract. In recent projects, I have created Typescript interfaces for the AJAX responses generated by my backend code. This ensures clarity for the frontend developer, whether ...

Adding an object with a composite key to an IndexedDB object store is not permitted as the key already exists within the store. This limitation occurs when attempting to add an entry

I am facing an issue with my objectStore where adding an object with the same productId but a different shopName triggers an error in the transaction showing: ConstraintError: Key already exists in the object store.. This is how I initialized the objectSto ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

Syntax for TypeScript generic promises definition

I'm struggling to fully grasp the definition of Promise in TypeScript, as shown below: /** * Represents the completion of an asynchronous operation */ interface Promise<T> { /** * Attaches callbacks for the resolution and/or rejectio ...

Updating and Preserving Content in Angular

I've encountered an issue while working on a code that allows users to edit and save a paragraph on the screen. Currently, the editing functionality is working fine and the save() operation is successful. However, after saving, the edited paragraph do ...

Steps for implementing a conditional rendering in your codeHere is a

I've encountered an issue while attempting to implement conditional rendering. The error I'm getting is Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'types&apos ...

React form submissions are not saving the state

I currently have dynamic components rendered from the server side, including a submit button component. The issue I am facing is that when I submit the form, the state reverts to its initial values instead of retaining the updated values set by child compo ...

What is the best way to use a generic callback function as a specific argument?

TS Playground of the problem function callStringFunction(callback: (s: string) => void) { callback("unknown string inputted by user"); } function callNumberFunction(callback: (n: number) => void) { callback(4); // unknown number inputt ...

Error: An unauthorized attempt was made to modify property settings for certain users, which are designated as read-only

Within my Ionic app, there exists a specific page where users have the ability to modify information related to a particular city. What I aim to achieve is for these modifications to only be visible to other users who are also located within the same "City ...

The ESLINT_NO_DEV_ERRORS flag appears to be ineffective in my Typescript project

Currently, my project involves using the following tools: Yarn Typescript Create React App ESLint Make (Makefile) Fish shell During development, I encounter ESLint errors that prevent my project from compiling. To run my project, I use make run, which es ...

Getting started with Angular 2 using NPM version 3.10.6 and Angular CLI 1.0.0

I am having trouble when I run 'NPM start,' all I get is Below are the files in my project: package.json { "name": "angular2-quickstart", "version": "1.0.0", // rest of the package.json file continues... } tsConfig.json { "compilerOp ...

When trying to convert a jest test to typescript, an error message may be encountered stating: "SyntaxError: Unable to

As I delved into the clear and concise jest documentation, I managed to successfully implement this test: const { spawnSync } = require('child_process'); const ls = spawnSync('ls', ['-lh', '/usr']); const unexistent ...

Passing a map from the SpringBoot backend to the Angular view and storing it in LocalStorage

I'm facing a challenge with this task. I am trying to transfer a Map from my Spring Boot backend to an Angular application. Controller @GetMapping("/dict") public Map<String, String> getAll(){ return dictionaryService.getAll(); } @ ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

What is the process for converting an image into base 64 using Angular 5?

Is there a way to convert an image into base 64 using angular5 when the image is sourced from Facebook or Google authentication API? I seem to be encountering an issue, what could I be doing wrong? getBase64Image(img) { var canvas = document.createEleme ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...

This error occurred: "Property 'release' cannot be read because it is undefined."

Hello everyone! I'm in need of some assistance. I am trying to test my service tree with a specific structure. Here is an overview of my test: describe(`Service selector`, () => { describe(`getCurrentServiceTree`, () => { it(`should bui ...

Challenges encountered while implementing generic types in TypeScript and React (including context provider, union types, and intersection

I have a fully functional example available at this link: The code is working properly, but TypeScript is showing some errors. Unfortunately, I've run out of ideas on how to make the code type safe. I've searched extensively for examples that ma ...