Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript add a prefix to each type in a string union type

Is it possible to create a type from a union type where each element of the union will be transformed according to a pattern? (I just need to put a prefix).

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes, that is possible. Since TypesScript 4.1 you can use a Conditional Type in combination with a Template Literal Type like so:

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

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

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

Or directly define the generic to extend string in order to pass a prefix:

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading