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

You've successfully subscribed to SmartLogic Blog
Great! Next, complete checkout for full access to SmartLogic Blog
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.