Set an Object's property name from a Variable in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 23, 2022

banner

Photo from Unsplash

Set an Object's property name from a Variable in TypeScript #

Use computed property names to set an object's property name from a variable in TypeScript, e.g. const obj: Person = {[myVar]: 'Tom'}. The computed property names feature allows us to dynamically determine the property names of an object.

index.ts
type Person = { name: string; country: string; }; const myVar = 'name'; const obj: Person = { [myVar]: 'Tom', country: 'Chile', }; console.log(obj); // 👉️ {name: 'Tom', country: 'Chile'}

We set an object's property name from a variable using computed properties.

All we had to do is wrap the variable in square brackets [] for it to get evaluated before being assigned as a property on the object.

Here is an example that uses a function.

index.ts
type Person = { name: string; country: string; }; const myVar = 'name'; function getObj(): Person { return { [myVar]: 'Tom', country: 'Chile', }; } const obj1 = getObj(); console.log(obj1); // 👉️ {name: 'Tom', country: 'Chile'}

The expression between the square brackets gets evaluated, which means that you could construct the object's property name by using multiple variables or concatenating strings.

index.ts
const myVar = 'na'; const myVar2 = 'me'; // 👇️ const obj: { [x: string]: string; country: string;} const obj = { [myVar + myVar2]: 'Tom', country: 'Chile', }; console.log(obj); // 👉️ {name: 'Tom', country: 'Chile'}

But notice that TypeScript was not able to type the property in the object as name and instead typed it as a more generic index signature of [x: string] (any string property).

If you are sure about the value the expression will evaluate to, you can use a type assertion.

index.ts
const myVar = 'na'; const myVar2 = 'me'; // 👇️ const obj: const obj: { name: string; country: string;} const obj = { [(myVar + myVar2) as 'name']: 'Tom', country: 'Chile', }; console.log(obj); // 👉️ {name: 'Tom', country: 'Chile'}

Now the object is typed correctly and we can still use the dynamic nature of the computed property names feature.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.