TypeScript: Using Variables to Set Object Keys

Updated: March 20, 2022 By: Hadrianus 2 comments

There might be cases where you want to use a variable as a dynamic key of an object in TypeScript. The following examples will show you how to do that.

Example 1

const key1 = 123; // number
const key2 = 'puppy'; // string key

const obj = {
  [key1]: 'Value 1',
  [key2]: 'Value 2'
}

console.log(obj);

Output:

{ '123': 'Value 1', puppy: 'Value 2' }

Example 2

interface MyInterface {
  [key: string]: number
}

const key1 = 'a';
const key2 = 'b';
const key3 = 'c';

let myObj: MyInterface;
myObj = {
  [key1]: 1,
  [key2]: 2,
  [key3]: 3
}

console.log(myObj);

Output:

{ a: 1, b: 2, c: 3 }

Further reading:

You can also check out our TypeScript category page for the latest tutorials and examples.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
1234
1234
1 month ago

you saved the day

m.c
m.c
5 months ago

great!

Related Articles