Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: is it possible to create a mapped union type?

Tags:

typescript

Is it possible to combine the "mapped types" and "union types" features to create an expression that takes the following interface as an input:

interface AwaActionTypes {
  CLICKLEFT: 'CL';
  CLICKRIGHT: 'CR';
  SCROLL: 'S';
  ZOOM: 'Z';
  RESIZE: 'R';
  KEYBOARDENTER: 'KE';
  KEYBOARDSPACE: 'KS';
  OTHER: 'O';
}

And produces a type that is the equivalent of the following union type alias:

type AwaActionType: 'CL' | 'CR' | 'S' | 'Z' | 'R' | 'KE' | 'KS' | 'O';

I tried using combinations of keyof, |, etc. Didn't land on something that worked. Didn't see anything in the handbook either.

like image 211
Jeremy Danyow Avatar asked May 02 '17 21:05

Jeremy Danyow


People also ask

Is it possible to combine types in TS?

An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need.

Is there a map type in TypeScript?

The Map is a new data structure introduced in ES6 so it is available to JavaScript as well as TypeScript. A Map allows storing key-value pairs (i.e. entries), similar to the maps in other programming languages e.g. Java HashMap.

How do I create a union in TypeScript?

TypeScript - Union In the above example, variable code is of union type, denoted using (string | number) . So, you can assign a string or a number to it. The function parameter can also be of union type, as shown below. In the above example, parameter code is of union type.

What is a mapped object type TypeScript?

A mapped type is a generic type which uses a union of PropertyKey s (frequently created via a keyof ) to iterate through keys to create a type: type OptionsFlags < Type > = { [ Property in keyof Type ]: boolean; };


1 Answers

It's a combination of keyof and lookup type

type AwaActionType = AwaActionTypes[keyof AwaActionTypes];
like image 142
artem Avatar answered Oct 07 '22 02:10

artem