Uncovering the types of objects in TypeScript

Can TypeScript infer the type based on the content of an object?

For example:

type MyKeyList =
    | "A"
    | "B"
    | "C"
    ;

type MyType<T extends MyKeyList> = {
    type: T,
    value: T extends "A"
        ? 1
        : T extends "B" ? 2 : 3
};


// Is there a way to perform this kind of check?
// Or is it simply not possible.
const MyObject: MyType = {
    type: "B"
}

Is there any method to achieve dynamic types like this?
Or is it just a limitation of TypeScript.

edit

The example above is simplified. Here is a more complex case I'm working with. The following type may not be practical, as it's just for demonstration purposes.


type Type1 = 
    | "A" | "B" | "C" | ... | "Z";

type Type2 = 
    | "AA" | "BB" | "CC" | ... | "ZZ";

type Type3 = true | false | "AAA" | "BBB" | "CCC";

type Field1Type<
    T extends Type1, 
    S extends ("AA" | "BB" | "CC" | undefined) = undefined
> = (value: number) => `${T}-${S}-${number}`;

type Field2Type<T extends ("X" | "Y" | "Z")> = 
    (value: boolean) => `${boolean}-${T}`;

type Field3Type<
    T extends Exclude<Type1, "X" | "Y" | "Z">,
    S extends ("AA" | "BB" | "CC")
> = (value: string) => `${T}-${string}-${S}`

type MyType<
    T extends Type1, 
    S extends Type2, 
    U extends Type3
> = {
    t: T,
    s: S,
    u: U,

    field1: U extends true 
        ? Field1Type<T>
        : S extends ("AA" | "BB" | "CC")
            ? Field1Type<T, S>
            : never,

    field2: T extends ("X" | "Y" | "Z")
        ? Field2Type<T>
        : never,

    field3: U extends (true | false)
        ? never
        : T extends ("X" | "Y" | "Z")
            ? never
            : S extends ("AA" | "BB" | "CC")
                ? Field3Type<Exclude<T, "X" | "Y" | "Z">, S>
                : never,
};


const tmp: MyType = {
    t: "A",
    s: "AA",
    u: true,
};

Answer №1

One method recommended by jcalz is to utilize this particular approach in order to unwrap generics into a union, especially for types with multiple nested generic arguments.

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

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...

Tips for successfully importing $lib in SvelteKit without encountering any TypeScript errors

Is there a way to import a $lib into my svelte project without encountering typescript errors in vscode? The project is building and running smoothly. import ThemeSwitch from '$lib/ThemeSwitch/ThemeSwitch.svelte'; The error message says "Canno ...

What techniques can I use to adjust the size of an image through zooming in and out?

In my custom gallery component, the crucial code section looks like this: <Gallery> <Header> <img src={galleryIcon} alt='Galley icon' /> <h1>My Gallery</h1> </Header> ...

Obtaining JSON data in React Native without prior knowledge of the key

When I receive this type of data, the keys are common but the items vary. How can I extract and add this data to my list of categories? { "99": "Venues", "100": "Party Supplies", "101": "Enter ...

The Proper Way to Position _app.tsx in a Next.js Setup for Personalized App Configuration

I've been working on a Next.js project and I'm currently trying to implement custom app configuration following the guidelines in the Next.js documentation regarding _app.tsx. However, I'm encountering some confusion and issues regarding the ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

Compiling TypeScript to JavaScript with Intellij IDEA while preserving the folder hierarchy

Seeking assistance with maintaining directory structure when compiling Typescript to Javascript in Intellij Idea. The current directory setup is as follows: root - ts - SomeClass1.ts - SomeFolder - AwesomeClass2.ts - tsc The desired compiled file ...

tips for preventing issues when the data array is empty

Here is the JSON data that I am dealing with: { "id": 43, "dataEvento": "2022-09-01T00:00:00.000+0000", "dataInvio": null, "idComunicazioneAssociata": null, "certificatoMedico" ...

Display the new data from an array that has been created following a subscription to Angular Firestore

I am struggling to access the content of a variable that holds an array from a Firebase subscription. The issue I am facing is that I am unable to retrieve or access the value I created within the subscription. It seems like I can only use the created valu ...

Comparing Fluid-Framework to Signal-R: Understanding the Distinguishing Factors

Query: Recently, Microsoft unveiled the Fluid-Framework on GitHub. What are the steps to replace Signal-R with Microsoft's Fluid-Framework and what are the main differences? Scenario: It appears that Fluid supports collaboration and data synchronizat ...

Set up a SQS queue to receive notifications from an SNS topic located in another AWS account by using AWS CDK in TypeScript

Looking to establish a connection between an SQS queue and an SNS topic located in a different account using CDK (TypeScript). Presented below is the code snippet (contained within a stack) that I believe should facilitate this integration. However, I have ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

Warning in Typescript: potential undefined access detected when strict mode is enabled

When using Typescript with "strict": true in the tsconfig.json, a common issue arises where warnings are not triggered for potentially undefined properties, as shown by this code snippet: let x: any = { test: false } let y = x.asdf // no warning issued ...

The functionality of connect-flash in Express JS is compromised when used in conjunction with express-mysql-session

I am facing a unique issue in my project. I have identified the source of the problem but I am struggling to find a solution. My project utilizes various modules such as cookie-parser, express-mysql-session, express-session, connect-flash, passport and m ...

Using ng-if to evaluate multiple numerical values

I have multiple questionnaires, and I'm looking to use *ngIf to control which ones are displayed in a specific div. Currently, I'm handling this by specifying each individual question number: <div *ngIf = "questionNo!= '00' &&a ...

Hold off until the operation finishes executing and then deliver Angular 6

Is there a way to delay the subscribe function until my logic is complete and the transform method has updated the keys object? transform(value: any, args:string) : any { let keys = []; this.http.get('src/app/enum-data/enum.json').subsc ...

Tips for handling missing environment variables during the build process in a Node.js project

My current setup involves using a .env file to store variables for my TypeScript Node project. I am able to check for missing environment variables during runtime and throw an error if any are not present. export const SOME_KEY = process.env.SOME_KEY || &q ...

Issue encountered while implementing async functionality in AngularFireObject

I'm encountering difficulties with the async feature in AngularFireObject. Is there a solution available? Snippet from HomePage.ts: import { AngularFireObject } from 'angularfire2/database'; export class HomePage { profileData: Angu ...

Tips on assigning array union as the return type of a function

I am working with a function parameter that accepts an array union, like this: (ClassA|ClassB)[]. How can I return either ClassA[] or ClassB[] from the function? When attempting to return type (ClassA|ClassB)[], I encounter the following error: Assig ...

What steps can be taken to ensure the visibility and accessibility of two vertically stacked/overlapped Html input elements in HTML?

I have encountered a challenge with my HTML input elements. There are two input elements that overlap each other, and I would like to make both inputs visible while only allowing the top input to be editable. I have tried several approaches involving z-ind ...