How to Use Variables to Set Object Keys in TypeScript

Updated: December 3, 2023 By: Khue 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 }

That’s it. Happy coding and have fun with TypeScript!