Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Enum as restricted key type in Typescript

Tags:

typescript

The question is can enum be used as a key type instead of only "number" or "string" ? Currently it seems like the only possible declaration is x:{[key:number]:any} where key can be of type "number" or "string". Is it possible to make something like in this example:

Example:

enum MyEnum {     First,     Second }  var layer:{[key:MyEnum]:any}; 
like image 443
Hivaga Avatar asked May 29 '17 12:05

Hivaga


People also ask

Can I use enum as type in TypeScript?

Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

Can you use an enum as a type?

Just like other data types in TypeScript, we can use enums as function parameters or return types, like this: enum Weekend { Friday = 1, Saturday, Sunday } function getDate(Day: string): Weekend { if ( Day === 'TGIF') { return Weekend.Friday; } } let DayType: Weekend = getDate('TGIF');

What can I use instead of enums TypeScript?

Alternative 1: String Unions This solution uses a union of string literal types. TS gives great autocompletes for these, and gives helpful error messages if you make type errors. Pros of the approach: Both the definition and use sites are readable and no-boilerplate.

Is enum a type or value TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.


2 Answers

Since 2018, there is an easier way in Typescript, without using keyof typeof:

let layer: { [key in MyEnum]: any} 

To not have to include all keys:

let layer: { [key in MyEnum]?: any} 
like image 192
Hugo Elhaj-Lahsen Avatar answered Sep 30 '22 03:09

Hugo Elhaj-Lahsen


Yes. Just type

let layer:{[key in keyof typeof MyEnum]: any} 

The keyof keyword is available since Typescript 2.1. See the TypeScript documentation for more details. Using only keyof for enums wouldn't work (you'd get the keys of the enum type and not the enum constants), so you have to type keyof typeof.

like image 45
Sebastian Avatar answered Sep 30 '22 01:09

Sebastian