Associate union with interface attributes

Can a union type be transformed into an interface in Typescript?

My Desired Outcome

If we have a union type A:

type A = 'one' | 'two' | 'three';

I want to convert it to interface B:

interface B {
    one:   boolean;
    two:   boolean;
    three: boolean;
}

Answer №1

Discover the Magic of Mapped Types with this simple example:

type X = 'red' | 'blue' | 'green';

type Y = {
    [item in X]: boolean;
};

Y results in:

{
    red:   boolean;
    blue:  boolean;
    green: boolean;
}

Explore More!

And don't forget, as Aleksey L. suggests, there's a handy utility type called Record:

type Y = Record<X, boolean>;

With mapped types, you can even vary the property types using conditional types:

type X = 'red' | 'blue' | 'green';

type Y = {
    [item in X]: item extends 'red' ? number : boolean;
};

Y transforms into:

{
    red:   number;
    blue:  boolean;
    green: boolean;
}

Don't Miss Out on Trying It Yourself!

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

utilize a modal button in Angular to showcase images

I am working on a project where I want to display images upon clicking a button. How can I set up the openModal() method to achieve this functionality? The images will be fetched from the assets directory and will change depending on the choice made (B1, ...

I'm having trouble getting my Node.js and TypeScript project to run because I keep encountering the error message ".ts is recognized as an unknown file extension."

I encountered the following error message: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" This issue arose after inserting "type": "module" into the package.json package.json { "name": &qu ...

Managing onChange in a ReactJs project

Currently, my React tsx page features input boxes like the following: <textarea value={this.state.myData!.valueOne} onChange={(e) => this.handleValueOneChange(e)}/> <textarea value={this.state.myData!.valueTwo} onChange={(e) => thi ...

Angular 4 HTTP Requests Failing to Retrieve JSON Data

I am currently working with the following method in my Typescript: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const params: string = [ `onlyActive=${onlyActive}`, `page=${page}` ].join('&&apo ...

Angular ngx-translate not displaying image

My Angular application is utilizing ngx-translate to support multiple languages. I am trying to dynamically change an image based on the language selected by the user. However, I am facing difficulty in updating the image when a language is clicked. The ap ...

Downcasting on "this" is not supported in Typescript

In the example below, the TypeScript compiler does not allow for a direct cast of this to Child. However, it is possible to achieve this using an intermediate variable like 'temp' or double casting as shown in the commented lines. Is this behavio ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

Exploring the use of TypeScript and Webpack to read non-JavaScript files in Node.js

I'm working on a backend NodeJS setup written in TypeScript that is using webpack for compilation. However, I encountered an error when trying to read a text file even though I confirmed that the file source/test.txt is being copied to the build fold ...

Typescript is throwing an error stating that the type 'Promise<void>' cannot be assigned to the type 'void | Destructor'

The text editor is displaying the following message: Error: Type 'Promise' is not compatible with type 'void | Destructor'. This error occurs when calling checkUserLoggedIn() within the useEffect hook. To resolve this, I tried defin ...

There is an error in the TypeScript code where it is not possible to assign a string or

I'm struggling to resolve a typescript error. Upon checking the console log, I noticed that the regions returned by Set are an array of strings, which aligns perfectly with the region type in my state. Why isn't this setup working as expected? S ...

I'm on the lookout for a component similar to angular-ui-tree that is compatible with angular

As a new developer, I am in search of a component similar to: But specifically for Angular 6, with all the same functionality (drag-and-drop capability, nested items, JSON structure, etc.). I have come across some components that either lack dragging fun ...

Tips on adding an item to an array with React hooks and TypeScript

I'm a beginner with a simple question, so please bear with me. I'm trying to understand how to add an Object to the state array when a form is submitted. Thank you for your help! interface newList { name: string; } const ListAdder = () => { ...

Different categories combined into a singular category

Trying to define a type that can be one of two options, currently attempting the following: type TestConfig = { file: string; name: string; } type CakeConfig = { run: string; } type MixConfig = { test: TestConfig | CakeConfig }; const typeCheck: M ...

Why is the value always left unused?

I am having an issue with handling value changes on focus and blur events in my input field. Here is the code snippet: <input v-model="totalAmount" @focus="hideSymbol(totalAmount)" @blur="showSymbol(totalAmount)" /> ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

React.js: You cannot call this expression. The type 'never' does not have any call signatures

Could someone help me troubleshoot the error I'm encountering with useStyles? It seems to be related to Typescript. Here's the line causing the issue: const classes = useStyles(); import React from "react"; import { makeStyles } from & ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...

The node version in VS Code is outdated compared to the node version installed on my computer

While working on a TypeScript project, I encountered an issue when running "tsc fileName.ts" which resulted in the error message "Accessors are only available when targeting ECMAScript 5 and higher." To resolve this, I found that using "tsc -t es5 fileName ...

Relocating the node_modules folder results in syntax errors arising

I encountered a perplexing syntax error issue. I noticed that having a node_modules directory in the same location I run npm run tsc resolves the issue with no syntax errors. However, after relocating the node_modules directory to my home directory, ~ , a ...

How can I define types for (const item of entries) in Typescript?

I attempted for (const ElementType as element of elements ) {} or for (const ElementType of elements as element) {} However, neither of these options is correct. ...