Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types:

  • Uppercase
  • Lowercase
  • Capitalize
  • Uncapitalize

For more information, refer to the official documentation.

Although it may seem unlikely, I'm seeking clarification on a specific issue.

I have an interface with fixed properties and some that may vary. My goal is to extract the potentially evolving properties into a distinct type. These properties follow a pattern of incremental numbers from 1 to 3. To provide clarity, consider the example below:

interface A {
  propA: string; // not needed
  propB: string; // not needed
  propC: string; // not needed

  propD1: string;
  propD2: string;
  propD3: string;

  propE1: string;
  propE2: string;
  propE3: string;

  propF1: string;
  propF2: string;
  propF3: string;
}

Implementing this seems challenging, if not impossible... But ideally, I'd like a type similar to this:

MagicType<A> should yield 'propD' | 'propE' | 'propF'.

In essence, it should detect properties ending with 1, 2, or 3.

While this task may exceed the capabilities of existing template literal functions (Uppercase, Lowercase, Capitalize, Uncapitalize), I wonder if there are provisions for creating custom intrinsic types at present?

Your insights and feedback would be greatly appreciated!

Answer №1

"Intrinsic" refers to being built into the compiler, so technically you would have to modify the compiler for a strict solution.

However, in practice, you can achieve the desired outcome without making your type intrinsic:

type EasyAs123<K extends string> = K extends `${infer U}${1 | 2 | 3}` ? U : never

// type Test = "propD" | "propE" | "propF"
type Test = EasyAs123<keyof A>

Interactive Demo 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

Having difficulties incorporating a separate library into an Angular project

My typescript library contains the following code, inspired by this singleton example code export class CodeLib { private static _instance: CodeLib; constructor() { } static get instance(): CodeLib { if(!this._instance){ ...

What is the trick to accessing an object's key and value when you are unsure of the object's

Currently, I am in the process of constructing a React component that is designed to receive an array of objects. However, I have encountered a question: Is there a way for me to retrieve both the key and value of an object within the map function without ...

Limit function parameters to only accept values with matching keys

I am relatively new to using TypeScript and am currently working on a project that involves handling various shapes of data from different sources. My goal is to pass this data to different aggregator classes, with one aggregator class corresponding to eac ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

Prevent the event listener from continuously triggering

I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again. The problem arises when this event is ...

Compiling TypeScript files for Angular 2 with Atom can be quite time-consuming

Currently, I am utilizing Angular 2 RC-6 by referencing the Angular2 Documentation. However, I have encountered an issue with Atom being too slow to compile my '.ts' files. Interestingly, when I relocate my tsconfig.json file from the root folder ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

Creating a personalized Cache Module in Nest JS involves implementing a custom caching mechanism tailored to

I need help with implementing a custom CacheModule in NestJS. The guide only shows how to connect the cache directly to the main module of the AppModule application. What is the correct way to define and implement a custom cache module? My attempt at crea ...

Trying out the results of angular services

Seeking assistance in understanding the current situation: I believe a simple tour of heroes app would be helpful in clarifying, I am looking to set up some tests using Jest to verify if the behavior of a service remains consistent over time. This is ho ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi ...

Optimal Approach for Redirecting Authorization

I'm currently working on setting up an authorization feature for my Angular application. Here is the detailed process I am following: First, I generate a state and code in the front end. Upon clicking the login button, the application redirects to /a ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

Building upon a React component with TypeScript, we are extending its functionality using a generic type and then leveraging this same generic type

In my component, I have a setup where it takes two props - node and patchCurrentNode. import { css } from '@emotion/react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import React, { PropsWithChildren, useStat ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

What is the best way to send two separate properties to the selector function?

My selector relies on another one, requiring the userId to function properly. Now, I want to enhance the selector to also accept a property named "userFriend". However, there seems to be an issue with passing this new parameter, as it only recognizes the ...

What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' arg ...

Ion-List seamlessly integrates with both ion-tabs and ion-nav components, creating a cohesive and dynamic user interface

On my homepage, there is an ion-list. Sometimes (not every time), when I select an item in this list or navigate to the register page using "this.app.getRootNav().push("ClienteCadastroPage")", and then select an input in the registerPage or descriptionPage ...