Only map property type when the type is a union type

My goal is to create a mapping between the keys of an object type and another object, following these rules:

  • Each key should be from the original type
  • If the value's type is a union type, it should have { enum: Array }
  • If the value's type is not a union type, it should have { enum: never }

For example:

type OriginalType = {
    foo: "a" | "b";
    bar: "c";
    foobar: Record<string, string>;
};

type MappedType<T> = { ... };

type ResultType = MappedType<OriginalType>;

// ResultType = {
//    foo: { enum: ["a", "b"] },
//    bar: { enum: never },
//    foobar: { enum: never },
//}

I am able to map the keys and values to a new type, but I'm struggling with determining whether a type is a union type:

type IsUnion<T> = ...

type MappedType<T> = {
    [K in keyof T]: IsUnion<T[K]> extends true ? { enum: Array<T[K]> } : never;
};

Answer №1

When working with TypeScript, it can be challenging to distinguish unions from non-unions directly. Therefore, any custom implementation of this functionality may encounter unexpected edge cases. One way to detect a union type is by utilizing distributive conditional types to divide a type into its union members and compare each member with the original unsplit type. If the type is a union, each piece will differ from the whole, while a non-union type will have only one identical piece. Here's an example:

type IsUnion<T, U = T> = 
  T extends unknown ? [U] extends [T] ? false : true : never;

In the above code snippet, I've demonstrated how default generic type arguments can be used to verify whether a given type is a union or not. Testing this out:

type U = IsUnion<number>; // false
type V = IsUnion<string | number>; // true

The results seem accurate. For a practical example, consider applying this concept to map certain properties in a type based on whether they are part of a union or not:

type MappedType<T> = {
  [K in keyof T]: IsUnion<T[K]> extends true ? { enum: Array<T[K]> } : never;
};
// Further usage and results here...

This approach allows for dynamic checking and mapping of types within TypeScript programs. You can experiment further with the provided 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

Combining URL parameters into an object with NestJS's HTTP module

Is there a method for passing URL parameters to the httpService in nestjs? I want to improve the readability of this URL without resorting to Axios as nest has its own HTTPModule. Currently, this is how it looks and functions: const response = await this. ...

Ways to address the issue arising from the utilization of the "as" keyword

Every time I encounter this issue - why must I always provide all the details? type Document = Record<string, any> type FilteredDocument<T extends Document> = {[key in keyof T as T[key] extends (()=>void) ? never : key]: T[key]} const ...

The attribute 'prop' is not found on the type 'IntrinsicAttributes & TableProp'.ts(2322)

Encountering an error while trying to pass a prop to a React component for the first time. Despite looking at other posts for solutions, I have been unable to resolve it so far. Here is a snippet of my code: type TableProp = {}; function Table(prop: Tabl ...

Unable to utilize the namespace 'RouteComponentProps' as a specified type

When using TypeScript to define an interface that extends RouteComponentProp, I encountered some issues: VSCode error: [ts] Cannot use namespace "RouteComponentProps" as a type. Console error: Cannot use namespace 'RouteComponentProps' as a typ ...

Tips for transferring request variables/data from a middleware to another function in typescript

I need to authenticate a user's jwt token using middleware. This is the middleware I have: const authorized = (req: Request, res: Response, next: NextFunction) => { const token = req.header("token") if(!token){ return res.send("N ...

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...

I'm puzzled as to why I am unable to invoke a class method within this callback function. The error message indicates a TypeError: 'this' is undefined

Currently, I am troubleshooting a challenge in my Angular application that involve TypeScript. The issue lies within a method in a TypeScript class: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsApplied ...

The parameter 'prev: todoType[] => todoType[]' cannot be assigned to the type 'todoType[]'.ts(2345)

An issue has arisen with this.props.update as mentioned in the title import { useState } from "react"; import axios from "axios"; import { todoType } from "../../types/todo"; type sendResponse = { task: string; }; type getRe ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

Using Angular 5 to link date input to form field (reactive approach)

I'm encountering an issue with the input type date. I am trying to bind data from a component. Below is my field: <div class="col-md-6"> <label for="dateOfReport">Data zgłoszenia błędu:</label> <input type="date" formC ...

Tips for converting NULL% to 0%

When running my calculatePercents() method, I am receiving NULL% instead of 0%. Upon checking my console.log, I noticed that the values being printed are shown as NULL. calculatePercents() { this.v.global.total.amount = this.v.global.cash.amount + ...

Stop ngOnChanges from being triggered after dispatching event (Angular 2+)

In Angular 2+, a custom two-way binding technique can be achieved by utilizing @Input and @Output parameters. For instance, if there is a need for a child component to communicate with an external plugin, the following approach can be taken: export class ...

"Why is it that the onChange method of the antd table does not return an array of numbers for selectedRowKeys

In my current project, I am working on a Nextjs application that utilizes typescript and antd. The application includes a table component from antd which allows users to select rows. const rowSelection = { onChange: (selectedKeys: any[], selectedRows: M ...

The specified type '{ data: any; }' is incompatible with the type 'IntrinsicAttributes'. The property 'data' is not found in the type 'IntrinsicAttributes'

I'm encountering issues with the data property. interface Props { params: { slug: string }; } const Page = async ({ params }: Props) => { const data: any = await getPage(params.slug); // This section dynamically renders the appropriate orga ...

Encountering difficulties while utilizing Ramda in typescript with compose

When attempting to utilize Ramda with TypeScript, I encountered a type problem, particularly when using compose. Here are the required dependencies: "devDependencies": { "@types/ramda": "^0.25.21", "typescript": "^2.8.1", }, "dependencies": { "ramda ...

I encountered a SyntaxError while parsing JSON due to an absence of a number after a minus sign at position 1

I am trying to use the replicate model visoar/product-photo:edf42659dae0da88a26dba4912e7e4bb6c2fba25b1e1c6a5464cf220e467bce0, but when I provide it with an image and a prompt like on this page.tsx: "use client" import { LandingNavBar } from &apo ...

Utilizing Next.js and React to interact with Open AI through API requests

I'm currently experimenting with the OpenAI API to develop a chatbot using React, TypeScript, and Next.js. I am facing an issue where clicking the send button in the UI does not trigger any action. Even after adding console.log statements, nothing sho ...

Having trouble uploading images using Ionic/Angular to a PHP script

I've been working on incorporating image uploading functionality into my Ionic app. Despite reading multiple tutorials, I haven't been able to get it up and running successfully. I'm specifically aiming for the app to work smoothly in a web ...

How can one define a getter within an interface?

One of my classes is structured like this (only showing a portion here): export class LinkedListNode<t> extends windward.WrObject implements ILinkedListNode<t> { public get next(): LinkedListNode<t> { return this._next === thi ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...