Last updated: Feb 27, 2024
Reading timeยท3 min
To dynamically access an object's property:
keyof typeof obj
as the type of the dynamic key.obj[myVar]
.const obj = { name: 'Bobby Hadz', country: 'Chile', }; type ObjectKey = keyof typeof obj; const myVar = 'name' as ObjectKey; console.log(obj[myVar]); // ๐๏ธ Bobby Hadz
The keyof typeof syntax allows us to get a union type of the object's keys.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; // ๐๏ธ type ObjectKey = "name" | "country" type ObjectKey = keyof typeof obj; const myVar = 'name' as ObjectKey;
myVar
variable will only ever store a string that is equal to one of the keys in the object.Now we can access the object's property dynamically.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; // ๐๏ธ type ObjectKey = "name" | "country" type ObjectKey = keyof typeof obj; const myVar = 'name' as ObjectKey; console.log(obj[myVar]); // ๐๏ธ Bobby Hadz
This is needed because TypeScript is not always able to determine the type of a string to be as narrow as necessary.
If you try to set the type of the variable to be a union of the object's keys, you would get an error.
const obj = { name: 'Bobby hadz', country: 'Chile', }; // ๐๏ธ type ObjectKey = "name" | "country" type ObjectKey = keyof typeof obj; // โ๏ธ Error: Type 'string' is not assignable to type '"name" | "country"'. const myVar: ObjectKey = 'na' + 'me';
I've also written an article on how to get an object's key by value in TS.
The easiest way to get around this is to use a type assertion.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; // ๐๏ธ type ObjectKey = "name" | "country" type ObjectKey = keyof typeof obj; // ๐๏ธ const myVar: "name" | "country" const myVar = ('na' + 'me') as ObjectKey; console.log(obj[myVar]); // ๐๏ธ Bobby Hadz
You can also use a type assertion directly in the square brackets.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; // ๐๏ธ const myVar: string const myVar = 'na' + 'me'; // ๐๏ธ type ObjectKey = "name" | "country" type ObjectKey = keyof typeof obj; console.log(obj[myVar as ObjectKey]); // ๐๏ธ Bobby Hadz
However, with this approach, you have to use a type assertion every time you try to dynamically access the property on the object.
I've also written a guide on How to add a property to an object.
You can learn more about the related topics by checking out the following tutorials: