Iterating over Union types in typescript

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, allowing them to take on different types as needed. This flexibility enhances TypeScript's ability to model real-world scenarios more accurately.

Syntax of the union types is: type UnionType = Type1 | Type2 | Type3;


Union types offers the following benefits:

  • More accurately represents scenarios where a variable can have multiple possible types.
  • Enhances code expressiveness and type safety.

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:

  1. Using Template Literal Types:
  2. Using Distributive Conditional Types


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, they become distributive when given a union type:

Distributive Conditional Types



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:


Mansur Hamidov

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>"

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了