Identify the type of a characteristic based on the discriminant for the associated member of a discriminated union

In this discriminated union, the property id is assigned a different type based on the discriminant value:

type TableKind = 'administration' | 'data'

type AdministrationTableId = 'Modules' | 'Users' | 'Roles'
type DataTableId = number

type GenericIdentifier<K extends TableKind, ID> = { kind: K, id: ID }

type AdministrationTableIdentifier = GenericIdentifier<'administration', AdministrationTableId>
type DataTableIdentifier = GenericIdentifier<'data', DataTableId>

type TableIdentifier = AdministrationTableIdentifier | DataTableIdentifier

A new generic type needs to be defined that can determine the type of the id property based on the discriminant:

type GetTableIdType<K extends TableKind> = ???

type AdminId = GetTableIdType<'administration'> // returns AdministrationTableID
type DataId = GetTableIdType<'data'> // returns DataTableId

Can such a type be created? How could this be accomplished?

Answer №1

For this task, you can utilize the Extract

type TableCategory = 'management' | 'information'

type ManagementTableId = 'Projects' | 'Employees' | 'Departments'
type InformationTableId = number

type Identifier<C extends TableCategory, ID> = { category: C, id: ID }

type ManagementTableIdentifier = Identifier<'management', ManagementTableId>

type InformationTableIdentifier = Identifier<'information', InformationTableId>

type TableIdentifier = ManagementTableIdentifier | InformationTableIdentifier


type GetTableIdType<C extends TableCategory> = Extract<TableIdentifier, { category: C }>['id']

type ProjectId = GetTableIdType<'management'> // returns ManagementTableID
type InfoId = GetTableIdType<'information'> // returns InformationTableId

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

Is there a way for me to convert my (TypeScript Definition) .d.ts file into a (JavaScript) .js file?

It seems that there are plenty of guides available on converting a file from .js to .d.ts, but not the other way around. Specifically, I have some code in .d.ts format and I would like to convert it into JavaScript. Can anyone offer assistance with this t ...

Guide to incorporating third-party libraries in Angular

Greetings, I have a common question regarding Angular and utilizing third-party libraries. As someone who does not frequently work with Typescript/Frontends, I am encountering an issue with Angular. Specifically, I am attempting to incorporate the node-htm ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

There seems to be an issue with the TypeScript compiler indicating that the property "forEach" is not found in

Hey, I've got an interesting situation with my Typescript interface: interface sprite_loading { [index: number]: { URL: string, name: string }} So, within the class, I'm creating an array like this: public spriteLoading: sprite_loading ...

Injecting JavaScript page level variable into an integrated Angular2 RC 1 application

To keep this brief, the issue I'm facing is an extension of a Stack Overflow question regarding passing page-level variables into an Angular 2 app service. Following Gunter's advice from the provided SO question, I attempted to pass a JavaScript ...

Whenever attempting to execute a protractor test using cucumber, a specific error message is displayed reading: "E/launcher - Process exited with error code 1"

Looking for some assistance. I seem to be stuck and can't pinpoint the issue. Package.json { "devDependencies": { "@cucumber/cucumber": "^7.0.0", "@serenity-js/core": "^2.25.7", "@s ...

Validate the data type based on the property

I have a CARD type that can be either a TEXT_CARD or an IMAGE_CARD: declare type TEXT_CARD = { type: "paragraph" | "h1" | "h2"; text: string; }; declare type IMAGE_CARD = { type: "img"; src: string; orient ...

Ensuring proper validation of sinon stub parameters in TypeScript

One of the unit tests in my code is responsible for checking the function arguments. it('Should retrieve product from the database', () => { stub(ProductModel, 'findById').returns({ lean: stub().returns({ total: 12 }), }); ...

Creating a div dynamically when a button is clicked using TypeScript

Currently, I am working with Angular 2.0 and have a piece of code in one of my HTML files: <div class="row"> <button class="btn btn-primary" (click)="addExtra">Add Extra</button> </div> I want to add a new div when the "Ad ...

How to ensure Angular mat-button-toggle elements are perfectly aligned within their respective groups

https://i.stack.imgur.com/Wjtn5.png Hello there, I'm trying to make the numbers in the first group match the style of the second group (noche, mañana...). I've set both the group and individual element width to 100%, but the numbers beyond 22 ...

Encountered an issue when attempting to send data using this.http.post in Angular from the client's perspective

Attempting to transfer data to a MySQL database using Angular on the client-side and Express JS on the server-side. The post function on the server side works when tested with Postman. Here is the code snippet: app.use(bodyParser.json()); app.use(bodyPa ...

Does anyone know how to retrieve the application version or import the package.json file? Can't seem to find the solution on

I need to display the version from the package.json file in my Angular application. To import it, I allowed importing json by adding a few extra lines in tsconfig.json: { "compilerOptions": { "module": "commonjs", ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...

Tips for setting a new key and value for an existing object in TypeScript

As I transition from JavaScript to TypeScript, I am currently working on creating a Discord bot using TypeScript to familiarize myself with the environment. However, I encountered an error when attempting to add new keys to an object that was previously cr ...

Determine the `overall` amount and adjust `overall` to equal `quantity * price` within a Typescript

I am looking to perform a calculation similar to this: total = quantity * price and continuously update the total when either the quantity or the price changes. template-output-snapshot app.component.html <form [formGroup]="editform" (ngSubm ...

The animation for the menuItem in the MenuBar in React is not functioning as expected

In my project, I am using React with TypeScript and implementing animations with framer-motion. One issue I am facing is that when the button is pressed to open the menubar, the menuItem should move according to the frame-motion animation but it is not. I ...

Guide on building an npm package that seamlessly allows for installation both locally and globally (-g) using webpack and typescript

As I work on developing an npm package with options for both local and global (-g) installations, I find myself puzzled by the distinctions between the src and lib directories and the purpose of the bin directory. In my previous projects, I typically util ...

The Spring Boot and Angular Fusion Application

Currently, I am in the process of developing a Spring Boot Application with Angular as the frontend and Spring-Boot for the backend. My goal is to create a deployable war. After researching various resources online, my current understanding is that Spring ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

The Cloudflare KV namespace remains unbound

After running wrangler dev, it appears that Worker KV is not being bound properly: ERROR in /src/handler.ts ./src/handler.ts 16:8-17 [tsl] ERROR in /src/handler.ts(16,9) TS2304: Cannot find name 'generalKV'. This is the content of handler. ...