Iterating over Union types in typescript
Before starting to show the possible ways of iterating over union types, I would like to give a short information about union types.
What are Union Types?
Union types provide a powerful mechanism for expressing the flexibility of variables
Syntax of the union types is: type UnionType = Type1 | Type2 | Type3;
Union types offers the following benefits:
How to Iterate over Union Types?
When you don’t want to repeat yourself, sometimes a type needs to be based on another type.
So how we can create a new union type based on another union type?
Let's say we have a following union type:
Now I want to create a new TEventHandler type that is based on TEvents union type. TEventHandler type should take each literal types from TEvents and add the 'on' prefix like the following:
So to do it there are 2 possible ways in typescript:
领英推荐
Lets start with the first one: Using Template Literal Types
By using Template Literal Types you can map unions:
Using Distributive Conditional Types
When conditional types act on a generic type
Using Union types in Mapped types
Mapped types build on the syntax for index signatures, which are used to declare the types of properties which have not been declared ahead of time:
A mapped type is a generic type which uses a union types for iteration keys for creating a type.
So we will continue with the above example to create a new type based on TResult type. What I want to have as a result is:
So in the following example TEventMapper will return the result similar to the above one:
Full-Stack Developer | PHP & Node.js Expertise | Building Scalable and Efficient Web Solutions | Front-End Developer | React & TypeScript Specialist
1 年In case with "type TEventMapper" another alternative could be "Record<TResult, (e: event) => void>"