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

let obj: { [key in MyEnum]: any} =
 { [MyEnum.First]: 1, [MyEnum.Second]: 2 };

To not have to include all keys:

let obj: { [key in MyEnum]?: any} =
 { [MyEnum.First]: 1 };

To know the difference between in and keyof typeof, continue reading.


in Enum vs keyof typeof Enum

in Enum compiles to enum values and keyof typeof to enum keys.


Other differences

With keyof typeof, you cannot change the enum properties:

let obj: { [key in keyof typeof MyEnum]?: any} = { First: 1 };
obj.First = 1;
// Cannot assign to 'First' because it is a read-only property.

... unless you use -readonly:

let obj: { -readonly [key in keyof typeof MyEnum]?: any} = { First: 1 };
obj.First = 1; // works

But you can use any integer key?!:

let obj: { [key in keyof typeof MyEnum]?: any} = { First: 1 };
obj[2] = 1;

keyof typeof will compile to:

{
    [x: number]: any;
    readonly First?: any;
    readonly Second?: any;
}

Note both the [x: number] and the readonly properties. This [x: number] property doesn't exist with a string enum.

But with in Enum, you can change the object:

enum MyEnum {
    First,  // default value of this is 0
    Second, // default value of this is 1
}

let obj: { [key in  MyEnum]?: any} = { [MyEnum.First]: 1 };
obj[MyEnum.First] = 1; // can use the enum...
obj[0] = 1;            // but can also use the enum value, 
                       // as it is a numeric enum by default

It's a numeric enum. But we can't use any number:

obj[42] = 1;
// Element implicitly has an 'any' type because 
// expression of type '42' can't be used to index type '{ 0?: any; 1?: any; }'.
// Property '42' does not exist on type '{ 0?: any; 1?: any; }'.

The declaration compiles to:

{
    0?: any;
    1?: any;
}

We allow only 0 and 1, the values of the enum.

This is in line with how you would expect an enum to work, there are no surprises unlike keyof typeof.

It works with string and heterogenous enums:

enum MyEnum
{
    First = 1,
    Second = "YES"
}

let obj: { [key in  MyEnum]?: any} = { [MyEnum.First]: 1, [MyEnum.Second]: 2 };
obj[1] = 0;
obj["YES"] = 0;

Here the type is:

{
    1?: any;
    YES?: any;
}

Get immutability with readonly:

let obj: { readonly [key in MyEnum]?: any} = { 
    [MyEnum.First]: 1,
};
obj[MyEnum.First] = 2;
// Cannot assign to '1' because it is a read-only property.

... which makes these keys readonly:

{
    readonly 1?: any;
    readonly 2?: any;
}

Summary

in Enum keyof typeof Enum
Compiles to enum values Compiles to enum keys
Does not allow values outside the enum Can allow numeric values outside the enum if you use a numeric enum
Can change the object, immutability opt-in with readonly Can't change enum props without -readonly. Other numeric values outside the enum can be

Use in Enum if possible.

Answer from xy2_ on Stack Overflow
Top answer
1 of 6
445

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

let obj: { [key in MyEnum]: any} =
 { [MyEnum.First]: 1, [MyEnum.Second]: 2 };

To not have to include all keys:

let obj: { [key in MyEnum]?: any} =
 { [MyEnum.First]: 1 };

To know the difference between in and keyof typeof, continue reading.


in Enum vs keyof typeof Enum

in Enum compiles to enum values and keyof typeof to enum keys.


Other differences

With keyof typeof, you cannot change the enum properties:

let obj: { [key in keyof typeof MyEnum]?: any} = { First: 1 };
obj.First = 1;
// Cannot assign to 'First' because it is a read-only property.

... unless you use -readonly:

let obj: { -readonly [key in keyof typeof MyEnum]?: any} = { First: 1 };
obj.First = 1; // works

But you can use any integer key?!:

let obj: { [key in keyof typeof MyEnum]?: any} = { First: 1 };
obj[2] = 1;

keyof typeof will compile to:

{
    [x: number]: any;
    readonly First?: any;
    readonly Second?: any;
}

Note both the [x: number] and the readonly properties. This [x: number] property doesn't exist with a string enum.

But with in Enum, you can change the object:

enum MyEnum {
    First,  // default value of this is 0
    Second, // default value of this is 1
}

let obj: { [key in  MyEnum]?: any} = { [MyEnum.First]: 1 };
obj[MyEnum.First] = 1; // can use the enum...
obj[0] = 1;            // but can also use the enum value, 
                       // as it is a numeric enum by default

It's a numeric enum. But we can't use any number:

obj[42] = 1;
// Element implicitly has an 'any' type because 
// expression of type '42' can't be used to index type '{ 0?: any; 1?: any; }'.
// Property '42' does not exist on type '{ 0?: any; 1?: any; }'.

The declaration compiles to:

{
    0?: any;
    1?: any;
}

We allow only 0 and 1, the values of the enum.

This is in line with how you would expect an enum to work, there are no surprises unlike keyof typeof.

It works with string and heterogenous enums:

enum MyEnum
{
    First = 1,
    Second = "YES"
}

let obj: { [key in  MyEnum]?: any} = { [MyEnum.First]: 1, [MyEnum.Second]: 2 };
obj[1] = 0;
obj["YES"] = 0;

Here the type is:

{
    1?: any;
    YES?: any;
}

Get immutability with readonly:

let obj: { readonly [key in MyEnum]?: any} = { 
    [MyEnum.First]: 1,
};
obj[MyEnum.First] = 2;
// Cannot assign to '1' because it is a read-only property.

... which makes these keys readonly:

{
    readonly 1?: any;
    readonly 2?: any;
}

Summary

in Enum keyof typeof Enum
Compiles to enum values Compiles to enum keys
Does not allow values outside the enum Can allow numeric values outside the enum if you use a numeric enum
Can change the object, immutability opt-in with readonly Can't change enum props without -readonly. Other numeric values outside the enum can be

Use in Enum if possible.

2 of 6
140

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.

🌐
TypeScript
typescriptlang.org › docs › handbook › enums.html
TypeScript: Handbook - Enums
In this generated code, an enum is compiled into an object that stores both forward (name -> value) and reverse (value -> name) mappings. References to other enum members are always emitted as property accesses and never inlined. Keep in mind that string enum members do not get a reverse mapping ...
🌐
DEV Community
dev.to › bwca › typing-object-keys-with-enum-values-using-typescript-4k23
Typing Object Keys With Enum Values Using Typescript - DEV Community
November 1, 2023 - A an array of additional values, passed to the converted function, left as an array of unknown, since the interface does not really care about them; V the type for the values, the mapped object keys will be pointing, this will provide the flexibility, we do not impose any restrictions; T this is the enum type, which will be passed.
🌐
GitHub
github.com › Microsoft › TypeScript › issues › 16687
Using const string enum as object key produces an indexed type · Issue #16687 · microsoft/TypeScript
May 20, 2017 - Keys from a string enum to be usable as static key names, similar to how constant strings are usable in computed key position. This probably should work even with non-const enums. const x: TestMap = { // currently works ['a']: 'string', ['b']: ...
Author   Jessidhia
🌐
Futurestud.io
futurestud.io › tutorials › typescript-get-all-keys-of-an-enum
TypeScript — Get All Keys of an Enum - Future Studio
January 18, 2024 - Here’s an example of getting a list of enum keys in TypeScript using Object.keys(): export enum FutureStudioBooks { retrofit = 'Retrofit Book', picasso = 'Picasso Book', glide = 'Glide Book', gson = 'Gson Book', 'gson-workbook' = 'Gson Workbook', } const keys = Object.keys(FutureStudioBooks) // ['retrofit', 'picasso', 'glide', 'gson', 'gson-workbook'] The keys property now contains the enum’s keys as an array.
Find elsewhere
🌐
GitHub
github.com › microsoft › TypeScript › issues › 19332
Allow enums as object literal keys · Issue #19332 · microsoft/TypeScript
October 19, 2017 - TypeScript Version: 2.5.3 · Code ... } Expected behavior: Enums are made of either numbers or strings, they should be allowed in object literals keys....
Author   aminpaks
🌐
Medium
obaranovskyi.medium.com › top-7-functions-youll-ever-need-to-work-with-enums-in-typescript-d8a75a445f2b
Top 8 functions you’ll ever need to work with Enums in TypeScript | by Oleh Baranovskyi | Medium
January 29, 2022 - It can be found here: https://fettblog.eu/typescript-better-object-keys/ So you can make an existing function even better if you want with ObjectKeys<T> type. We want to pass an enum and get the list of its values.
🌐
Technical Feeder
technicalfeeder.com › 2021 › 07 › mastering-enum-in-typescript
Typescript enum get value by key and key by value | Technical Feeder
April 12, 2023 - Explains how to get value by key, get key by value, and use an enum as an object key. Some functions don't behave as expected when an enum has number values or mixed type data. All enum-related solutions are on this page.
🌐
DEV Community
dev.to › ktrblog › js-ts-create-an-object-with-keys-based-on-enum-2k8c
[JS TS] How to create an object with keys based on enum - DEV Community
April 26, 2023 - enum ProductProperties { product_id = "id", product_name = "name", product_image = "image" } const enum2obj = (callback) => { return { ...(Object.fromEntries( Object.values(ProductProperties).map((val) => [ val, callback() ]) )), } } console.log( enum2obj(() => 'somevalue') )
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-get-enum-key-by-value
Get an Enum Key by Value in TypeScript | bobbyhadz
... Copied!// ✅ For Numeric Enums enum SizesNumeric { Small, Medium, Large, } console.log(SizesNumeric[0]); // 👉️ "Small" console.log(SizesNumeric[1]); // 👉️ "Medium" TypeScript enums are real objects and exist at runtime.
🌐
GitHub
github.com › Microsoft › TypeScript › issues › 14682
Use const enum values as keys of object literals · Issue #14682 · microsoft/TypeScript
November 17, 2016 - I want to use values of a const enum to define object literals ** Syntactic ** const enum E { Aa = 1, Bb = 2 } let obj = { E.Aa: "action a", E.Bb: "action b", }; Emit let obj = { 1: "action a", 2: "action b", }; Compatibility Since JS su...
Author   gdh1995
🌐
Python Guides
pythonguides.com › use-typescript-enums-as-object-keys
TypeScript Enums as Object Keys – Explained with Examples
June 10, 2025 - In this example, the rolePermissions object maps each role to an array of permissions. By using enums as keys, we ensure that only valid roles can be used. Check out: Create Custom Types from Enum Values in TypeScript
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript keyof enum
TypeScript keyof Enum | Definition, Syntax, Methods, and Examples
April 11, 2023 - Enums in TypeScript have their own uses as such, common usage is the string enums used to represent a set of static values selectable by the user itself. Most probably, we use keyof operator to create a type whose elements are the member keys. TypeScript keyof will yield a union containing property names/ keys possible to its operand. Most of the time, keyof operator precedes object ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Richinfante
richinfante.com › 2024 › 04 › 06 › ts-enum-record-required-keys
Typescript trick: Required enum values as keys
April 6, 2024 - // require all enum keys on record type EnumRecord<KeyType extends string, ValueType> = {[key in KeyType]: ValueType}; // some keys to use enum FeatureFlagKeys { DarkMode = 'dark_mode' DashboardMetrics = 'dashboard_metrics' CommentsView = 'comments_view' } // an object using enum values as keys const FlagMetadata : EnumRecord<FeatureFlagKeys, { title: string }> = { [FeatureFlagKeys.DarkMode]: { title: 'Dark Mode' }, [FeatureFlagKeys.DashboardMetrics]: { title: 'Enhanced Dashboard Metrics' }, } When we compile the above example, this will yield an error on typescript compilation, since FeatureFlagKeys.CommentsView is missing:
🌐
Sharooq
sharooq.com › how-to-access-keys-and-values-of-an-enum-in-typescript
How to access the keys and values of an Enum (string and numeric) in TypeScript.
July 10, 2022 - Now, let's see a numeric enum with ...NumericEnum[5]); //👈 Five ... Simply using the "Object.values()" or "Object.keys()" method will return both the keys and values in a combined array....
🌐
Webdevtutor
webdevtutor.net › blog › typescript-enum-in-object-key
Using TypeScript Enums in Object Keys: A Comprehensive Guide
By using the enum Fruit as keys ...s[Fruit.Apple]); // Output: 1.5 ... Using TypeScript enums as object keys is a powerful technique that can improve the robustness and maintainability of your code....