Prefix each type within a string union with a specific word

Can a new type be generated from a union type by applying a specific pattern to each element in the union? For example, adding a prefix:

type EventNames = 'DragStart' | 'Drag' | 'DragStop'
type HandlerNames = Prefix<'on', EventNames> // 'onDragStart' | 'onDrag' | 'onDragStop'

Answer №1

Achieving this is entirely feasible. Starting from TypesScript 4.1, you have the capability to utilize a Conditional Type alongside a Template Literal Type as demonstrated below:

type EventNames = "DragStart" | "Drag" | "DragStop";

type Prefix<K> = K extends string ? `on${K}` : K;
// --> "onDragStart" | "onDrag" | "onDragStop"

const myEvent: Prefix<EventNames> = "onDrag";

Alternatively, you can explicitly specify that the generic should extend string to input a prefix:

type EventNames = "DragStart" | "Drag" | "DragStop";

type Prefix<Prefix extends string, T extends string> = `${Prefix}${T}`;
const myEvent: Prefix<"on", EventNames> = "onDrag";

Answer №2

interface CombineStrings<A extends string, B extends string> {
  result: `${ A }${ B }`;
}

type Greetings = 'Hello' | 'Hi' | 'Hey';
type Phrases = CombineStrings<'Greeting:', Greetings>

const phrase1: Phrases = 'Greeting:Hi';
const phrase2: Phrases = 'Greeting:Hola'; // error!

Check out the code on StackBlitz:https://stackblitz.com/edit/typescript-98syrf?file=index.ts

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

Can template literal types be utilized to verify if one numeric value is greater than another?

I am attempting to define the Record for migration functions, which use the direction of the migration as the key: v${number}-v${number}, Considering that these migrations are all UP, they need to be validated as v${first-number}-v${first-number + 1} and ...

Enhance your Angular project with Swagger UI integration

Currently, I am working with Angular 10. I have set up the basic structure of my angular app and now I want to integrate the swagger-ui component into it. Initially, I came across a helpful example at https://github.com/agoncal/swagger-ui-angular6, and fo ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

Unable to execute functions on observable outcomes

Let's discuss an interface called Vehicle, a class named Car that implements it, and a method within the class titled isColorRed: export interface Vehicle{ color : string; } export class Car implements Vehicle{ color : string; constructo ...

Quick filtering of array containing RXJS Observables

As I embark on my Angular2 project, the developers have suggested using RXJS Observable over Promises. So far, I've successfully fetched a list of elements (epics) from the server. Now, my challenge is filtering these elements based on an ID. Below i ...

Using Typescript generics to deduce the type from the second parameter for utilization in the first slot

Here is the code snippet I'm working with: export type Subscribe<T extends object> = <U>( listener: (slice: U) => void, selector: (state: T) => U, ) => void // The actual implementation is not relevant const subscribe = {} as ...

Tips for leveraging Typescript in .vue files utilizing VS Code?

I have set up my development environment using Visual Studio Code, Vue 2 (webpack template), and Typescript. Below is the code snippet for my App.vue component: <template> <div id="app"> <navbar></navbar> [cont ...

Enhancing component and view functionality in Angular

Recently, I started working on Angular 11 and encountered a simple yet challenging question. Despite my best efforts, I have been unable to find a suitable answer. In an attempt to utilize Object-Oriented Programming (OOP) concepts within Angular, I create ...

Child component in Angular fails to recognize changes

When I update the product object from the parent component, the child component does not seem to detect the change and fails to update accordingly. product.ts export interface Product { productId: number; productName: string; lastUpdated: str ...

Employing Bazel in conjunction with Lerna and Yarn workspaces

It seems that a lot of people are currently utilizing lerna and/or yarn workspace. I'm thinking about either transitioning from them to Bazel, or perhaps integrating them with Bazel in conjunction with an example project for guidance. Take for insta ...

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

Combine two comma-separated strings in JavaScript to create an array of objects

I have two strings separated by commas that I want to transform into an array of objects. { "id": "1,2,3", "name": "test 1, test 2, test 3" } Is there a way to convert this into the desired object format? { &q ...

Angular error: Trying to access the toLowerCase property of an undefined value

I am facing an issue wherein, when I use the http.post method, I encounter an error stating "TypeError: Cannot read property 'toLowerCase' of undefined". I have attempted to downgrade Angular to version 8.0.0 in order to resolve this problem, but ...

Error message stating: rxjs and firebase encountered a TypeError when attempting to add property 0 because the object is not

My angular application interacts with firebase firestore as the backend database. I am working on a function to retrieve document snapshots from firestore in a generic way. Here is the code snippet where I encounter an error: /** * Get a 'liste ...

Unable to start an expo project in bare workflow using TypeScript

Can someone help me with setting up an expo bare workflow using TypeScript? I ran the command "expo init [project name]" in my terminal, but I can't seem to find the minimal (TypeScript) option. ? Choose a template: » - Use arrow-keys. Return to sub ...

What is the process of integrating Formik with Chakra using typescript?

I'm attempting to implement the following Chakra example in Typescript. <Formik initialValues={{ name: "Sasuke" }} onSubmit={(values, actions) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); actio ...

Configuring TypeScript for Firefox to recognize specific types such as browser.storage

As per the documentation from Mozilla, I should be able to utilize browser.storage.sync.get in my extension. However, I am encountering some challenges in getting TypeScript to recognize that I can use browser. I have attempted the following (which has wo ...

Standardized static class function

What is the correct method to reference a static property in extended classes using JavaScript? Consider the following javascript code: class Animal {} Animal.makeNoise = (language) => this.sounds[language]; class Dog extends Animal {} Dog.sounds = { ...

Is it possible to make functions dynamically adapt their behavior based on the types of arguments passed to them?

Consider this intricate collection of functions: interface Succes<a> { kind: 'succes' value: a } interface Failure<e> { kind: 'failure' error: e } type Result<a, e> = Succe ...

Creating pluggable components for JavaScript projects using Angular 2 and Typescript

Is it possible to develop pluggable components in Angular 2 using Typescript for a JavaScript project? While any JavaScript code is considered valid Typescript code, what happens when you have already completed your JavaScript(ES5) project and need to inco ...