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};
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.
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');
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.
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.
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}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With