Creating an Object Type from a String Union Type in TypeScript

How can I go about implementing this?

type ActionNames = 'init' | 'reset';

type UnionToObj<U> = {/* SOLUTION NEEDED HERE */}

type Result = UnionToObj<ActionNames>;
// Expected type for Result: `{ init: any, reset: any }`

I tried to write an implementation, but it didn't work as expected. It ran into the issue of union types extending covariance:

type UnionToObj<U> = U extends string ? { [K in U]: any } : never;
type Result = UnionToObj<'init' | 'reset'>;
// The expected Result type is `{ init: any, reset: any }`
// However, I ended up with a union object: `{ init: any } | { reset: any }`
// How can I fix this problem?

Main problems that need resolution:

  1. Converting string union types to object types
  2. Covariance of unions in TypeScript's extends clause

Answer №1

Exploring the concept of a mapped type, we encounter a simple example:

type UnionToObj<U extends PropertyKey> = { [K in U]: any }

type Result = UnionToObj<ActionNames>;
/* type Result = {
    init: any;
    reset: any;
} */

By constraining U to behave like a key, we define clear boundaries. Alternatively, if you prefer using a conditional type for checking, consider this approach:

type UnionToObj<U> = [U] extends [PropertyKey] ? { [K in U]: any } : never;

An important distinction lies in preventing distributed types through conditional checks, unlike your original unintentionally distributive type. By encapsulating the checked type within one-tuple brackets, union distribution is avoided.

Explore the code further in the Playground link.

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

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

How to send variables to a function when a value changes in TypeScript and Angular

As someone who is new to Angular and HTML, I am seeking assistance with the following code snippet: <mat-form-field> <mat-select (valueChange)="changeStatus(list.name, card.name)"> <mat-option *ngFor="let i of lists"> {{i.name}} ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

The incorrect initial state is causing issues in the Zustand state management on the Next.js server side

While utilizing zustand as a global state manager, I encountered an issue where the persisted states were not being logged correctly in the server side of nextjs pages. The log would only show the default values (which are null) and not the updated state v ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

Ensure to call the typescript file every time the page is reloaded or when a URL change occurs

Looking to integrate a session feature into my Angular 5 application. I aim to create a single TypeScript file that will handle user login validation. Is there a way to trigger this file every time the page reloads or the URL changes? Need guidance on im ...

Send information through a form by utilizing a personalized React hook

I'm having difficulty understanding how to implement a hook for submitting a form using fetch. Currently, this is what I have. The component containing the form: const MyForm = (): ReactElement => { const [status, data] = useSubmitForm('h ...

Angular 2 view becomes unresponsive following navigation

I have a web application powered by an API using Angular 2. I implemented a global service that extends angular2-sails, which handles responses to API calls. If the response includes 401 PLEASE_LOGIN, it redirects the user to the signup component. The iss ...

Establish a connection between two JSON files using the WordPress REST API

I have developed an app using ionic 2 that revolves around quotes. My goal is to manage these quotes (along with authors, categories, etc) using Wordpress and its REST API. Initially, I utilized normal posts for this purpose, but now I am exploring custom ...

Tips for automatically adjusting the row height in a table with a static header

On my page, I have a header, footer, and a single table with a fixed header. You can check out the code in the sandbox (make sure to open the results view in a new window). Click here for the code sandbox I am looking to extend the rows section so that i ...

Trouble with updating data in Angular 8 table

In Angular 8, I have created a table using angular material and AWS Lambda as the backend. The table includes a multi-select dropdown where users can choose values and click on a "Generate" button to add a new row with a timestamp and selected values displ ...

The Angular route successfully navigated to the page, but the HTML content was not

Whenever I select the Home option in the navigation bar, it takes me to the home URL but doesn't display the HTML content. Below is my app.routing.module.ts code: import { Component, NgModule } from '@angular/core'; import { RouterModule, Ro ...

Connect a datetime-local typed input to a Date attribute in Angular 2

Can a property of type Date in a component be bound to an HTML5 input with the type attribute set as datetime-local? For example, I have a component with the following property: public filterDateFrom: Date; And in my template, I am trying to bind this p ...

Ways to verify if a function has completed execution and proceed to invoke another function

I am seeking to verify if a user has chosen an item from the ngFor form and then redirect them to another page upon submitting the form with the updated value. HTML: <mat-select placeholder="Treatment" [(ngModel)]="model.TreatmentA" name="TreatmentA" ...

Utilizing Typescript with tfjs-node to effectively integrate the node-gpu version with regular node functionalities

I am facing challenges while running my Tensorflow.js node application with and without the GPU library. In vanilla JavaScript, examples show using require() for either @tensorflow/tfjs-node or @tensorflow/tfjs-node-gpu. However, in my TypeScript setup, I ...

Is it possible to close a tab while the chrome extension popup is still active?

I am currently developing a Chrome extension that reads the content of the current tab and performs a heavy task on the backend. If I were to close the tab while the process is ongoing, how can I allow the user to do so without waiting for the task to fi ...

What is the method for extracting date of birth data from .NET to Angular?

Struggling to fetch the date of birth from the database where it has been stored. After searching through multiple resources online, I am still unsure about how to accomplish this task. export class DetailsEmployeeComponent implements OnInit{ employeeD ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Updating the color of specific buttons using ngFor in Typescript and Angular 8

I have successfully implemented a feature where text is displayed word by word using an ngFor directive. Within the ngFor loop, there is an if-else statement that determines whether each word should be displayed as a <span> or a <button>. Now, ...