TypeScript: Using Variables to Set Object Keys

Last updated on March 20, 2022 The Shadow Loading... Post a comment

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
0 Comments
Inline Feedbacks
View all comments

You May Also Like