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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// 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]); } |
This post originally posted at https://blog.smartlogic.io/accessing-object-attributes-based-on-a-variable-in-typescript/