Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface.

const fields = [
  {
    id: 'textInput_1',
    fieldType: 'text',
  },
  {
    id: 'selectInput_1',
    fieldType: 'select',
  },
  {
    id: 'textInput_2',
    fieldType: 'text',
  },
] as const;

For my text and select input handlers, I want them to only accept keys that are associated with either a text or select field type.

To achieve this, I am creating a union of all possible keys like so:

type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;

type ItemKeys = ArrayElement<typeof fields>['id']; // 'textInput_1' | 'selectInput_1' | 'textInput_2'

Ultimately, I would like to dynamically generate the following type definitions:

type TextItemKeys = 'textInput_1' | 'textInput_2';
type SelectItemKeys = 'selectInput_1';

Answer №1

If you want to easily determine the type of a field, simply index it with a number like this: typeof field[number]

To specifically extract constituents of a union based on their fieldType, you can utilize the predefined Extract type:

type ItemType  = typeof fields[number];

type TextItemKeys = Extract<ItemType, { fieldType: 'text'}>['id'];
type SelectItemKeys = Extract<ItemType, { fieldType: 'select'}>['id'];

Try It Out Here

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

Having trouble understanding how to receive a response from an AJAX request

Here is the code that I am having an issue with: render() { var urlstr : string = 'http://localhost:8081/dashboard2/sustain-master/resources/data/search_energy_performance_by_region.php'; urlstr = urlstr + "?division=sdsdfdsf"; urlst ...

Facing issues with Angular 13 migration: Schema validation encountered errors stating that the data path "/error" needs to be a string

Currently in the process of migrating from Angular 8 to 13 and encountering an issue. I have been following the guidelines outlined on https://update.angular.io/, however, every time I attempt to build certain custom libraries from my application root fold ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Guide on navigating to a specific step within a wizard using Vue and TypeScript

In this wizard, there are 6 steps. The last step includes a button that redirects the user back to step 4 when clicked. The user must then complete steps 5 and 6 in order to finish the wizard. step6.ts <router-link to="/stepFour" ...

Exploring the world of child routing in Angular 17

I've been experimenting with child routing in Angular and encountered some confusion. Can someone explain the difference between the following two routing configurations? {path:'products',component:ProductsComponent,children:[{path:'de ...

Failure on the expect statement when comparing numbers in Jest..."The Jest magic number comparison is

I am currently conducting a test to verify that the magic number of a Buffer is in zip format. This involves extracting the first 4 bytes of the buffer into a string and comparing it with the magic number for zip, which is PK. const zipMagicNumber: str ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

Error: Unable to use import statement outside of a module when deploying Firebase with TypeScript

Every time I try to run firebase deploy, an error pops up while parsing my function triggers. It specifically points to this line of code: import * as functions from 'firebase-functions'; at the beginning of my file. This is a new problem for me ...

Using Typescript to define the type for React's useState() setter function whenever

I'm working on setting up a React Context to handle parameters mode and setMode, which act as getter and setter for a React state. This is necessary in order to update the CSS mode (light / dark) from child components. I'm encountering a Typescr ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...

Having trouble getting a Custom React Component from an external library to work with MUI styling

I am currently working with a React component that comes from a module located in the node_modules folder: type Props = { someProps: any }; export function ComponentA(props: Props) { const [value, setValue] = React.useState(""); return ( <Te ...

Using the `window` object in Jasmine with Angular, a mock can be created for testing purposes

In my current project, I have a function that I need to write unit tests for. Within this function, I am comparing the global objects window and parent using const isEqual = (window === parent). I am wondering what would be the most effective way to mock ...

Creating a custom extended version of Angular2 Http does not automatically provide injection of services

I'm struggling to understand this issue. I've created a custom class that extends Angular's Http class. import { Injectable } from '@angular/core'; { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, ...

Leveraging NgRx for Managing Arrays

export class Ingredient { public name: string; public amount: number; constructor(name: string, amount: number) { this.name = name; this.amount = amount; } } List of Ingredients: export const initialIngredients: Ingredient ...

Leveraging React Hooks to display a dynamic pie chart by fetching and mapping data from an API

I have a task where I need to fetch data from an API that returns an object containing two numbers and a list structured like this... {2, 1 , []} The project I'm currently working on utilizes 'use-global-hook' for managing state in Redux. T ...

Generate an observable by utilizing a component method which is triggered as an event handler

My current component setup looks like this: @Component({ template: ` ... <child-component (childEvent)="onChildEvent()"></child-component> ` }) export class ParentComponent { onChildEvent() { ... } } I am aiming to ...

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

Creating a signature for a function that can accept multiple parameter types in TypeScript

I am facing a dilemma with the following code snippet: const func1 = (state: Interface1){ //some code } const func2 = (state: Interface2){ //some other code } const func3: (state: Interface1|Interface2){ //some other code } However, ...