How to access object attributes based on a variable in Typescript

Typescript is obscurely particular with accessing attribute keys on objects that lack a generic signature. Adding generic signatures reduces type-safety though.

Here's a Typescript-friendly way to verify an attribute exists in an object, and then access that attribute.

// implicitly typed object
const myObj = {
  Hello: "world"

const myObjKey = "Hello";

// The commonly recommended way to check if an attribute exists,  
// which throws a no signature lint error Element implicitly 
// has any type (TS7053) in Typescript
// if (myObj[myObjKey]) {
//     ...
// }

// The 'in' way, which Typescript likes
if (myObjKey in myObj) {
  // Now that we've confirmed the attribute exists, it's
  // type-safe to recast myObjKey and access it as an attribute
  console.log(myObj[myObjKey as keyof typeof myObj]);

Header photo by Peter Lewicki on Unsplash