Sling Academy
Home/TypeScript/How to Use Variables to Set Object Keys in TypeScript

How to Use Variables to Set Object Keys in TypeScript

Last updated: December 03, 2023

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!

Next Article: Function Parameters Annotations in TypeScript: A Practical Guide

Previous Article: Intersection Types in TypeScript: Tutorial with Examples

Series: The First Steps to TypeScript

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)