Can a discriminated union be generated using mapped types in TypeScript?

Imagine you have an interface called X:

type X = {
  red: number, 
  blue: string
}

Can a union type Y be created using mapped types? If not, are there other ways to construct it at the type level?

type Y = {
  kind: "red"
  payload: number
} | {
 kind: "blue"
 payload: string
}

Answer №1

Absolutely, leveraging the fact that T[keyof T] represents a union of values in T, regardless of the type of T, is key here. By using a mapped type, you can create a new type with branches that align with the specific union you desire:

type NewType = { [Key in keyof OriginalType]: {category: Key, data: OriginalType[Key]} }[keyof OriginalType]

Check it out on the Playground!

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

The parameter cannot be assigned to type 'void' because it is of type 'Promise<unknown>'.ts(2345) - mockReturnValueOnce

Encountering an error while using the mockReturnValueOnce method, specifically 'Argument of type 'Promise' is not assignable to parameter of type 'void'.ts(2345)'. I attempted to solve it by writing the following code: .spyO ...

Angular 2: A guide to connecting Input with model property using getter and setter functions

I'm currently developing an Angular 2 web application. The model I have created consists of a few primary properties, along with other properties that are calculated based on those primary values. For each property in my model, I have implemented get ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

Can you explain the meaning of this TypeScript code snippet?

interface Configuration { [input: string]: any; } This is really puzzling to me, the 'input' is declared as a string type with any value? Appreciate your help. ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Interference of NestJS provider classes in separate event loops causing conflicts

I'm currently facing an issue where my shared library injectables are conflicting with each other. The bootstrap file initiates this file alongside a proxy server to start local microservices import { serviceA } from '@company/serviceA' imp ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

Guide on specifying a type for a default export in a Node.js module

export const exampleFunc: Function = (): boolean => true; In the code snippet above, exampleFunc is of type Function. If I wish to define a default export as shown below, how can I specify it as a Function? export default (): boolean => true; ...

Customizing the Android Back Button behavior in NativeScript for a single specific page

I am currently using NativeScript version 5.2.4 along with TypeScript. My goal is to disable the back button functionality in one specific page only, but I'm facing an issue where it also disables the back button behavior for child pages. Below is the ...

Retrieve the value of a property with a generic type

Within our angular6 project, we encountered an issue while using the "noImplicitAny": true setting. We realized that this caused problems when retrieving values from generic types. Currently, we retrieve the value by using current['orderBy'], bu ...

Error in Typescript persists even after short-circuit evaluation is used

Kindly review the provided code sample type type1 = string[] | undefined; let variable1 : type1 = undefined; console.log(variable1 && variable1.length); Upon attempting to run this code in Typescript Playground, an error is generated stating Pro ...

Utilize generic types as object properties in TypeScript

Is there a way to achieve something similar in TypeScript like the following: export type CoordinateSelector = <T>(d: Coordinate) => d[T]; export interface LinkVerticalLineProps { x: CoordinateSelector<'x'>; y: CoordinateSele ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

tslint: no use of namespace and module is permitted

I have recently acquired a legacy .ts file that I would like to update. Two warnings appear: 'namespace' and 'module' are disallowed and The internal 'module' syntax is deprecated, use the 'namespace' keyword ins ...

What is the method to incorporate type hints for my unique global Vue directives?

When I import or create a directive in an SFC file, I can receive TypeScript hints like this: import vFocus from 'my-custom-component-library'; View demo with ts hints However, if I globally register it in main.ts, the type hints are not availa ...

Ways to return bsDateRangePicker to its default value

I'm currently working on creating reactive forms using Angular 9 and integrating ngx-bootstrap. One issue I am facing is with the daterangepicker functionality. Whenever I utilize the form.reset() function, it clears the input field entirely instead o ...

What is the best way to decouple the data layer from Next.js API routes?

Currently, I am working on a project using Next.js with MongoDB. My setup involves using the MongoDB client directly in TypeScript. However, I have started thinking about the possibility of switching to a different database in the future and how that would ...

Issue encountered when trying to redirect after user creation on the backend

To persist a user, I use this method inside form-registrar-usuario.component: registrarUsuario(){ const role = this.route.snapshot.params["role"] if(role == "Proponedor"){ this.autorizacionService.registrarUsuario( role, thi ...

Executing a Parent Function from a Child Component in Angular 11

I have successfully passed values between Angular components using Input/Output several times before, but I am currently facing a unique situation for which I cannot find a solution: There are two components involved: home.component (parent component) T ...

Circular structure error occurred when attempting to convert an object to JSON, starting at an object constructed with the constructor 'Object'

I am facing an issue where I need to update a Medico from the collection, and I have successfully destructured the data of the Medico's name and email. Additionally, I have obtained the ID of the assigned hospital. However, I am having trouble sendin ...