I am trying to access a property of an object unknownObject: object
with a key propertyName
whose actual value is only known as runtime (and therefore can’t be narrowed down to anything else than string
).
Is there an idiomatic way to check for the presence of the key in the object, and then lookup the property, so that the property access does not require an explicit typeof propertyName as key typeof unknownObject
?
const unknownObject: object = {}
const propertyName: string = 'name' // Only known at runtime (so can't be narrowed more than `string`)
if (propertyName in unknownObject) {
console.log(unknownObject[propertyName]);
// Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
// No index signature with a parameter of type 'string' was found on type '{}'.(7053)
}
if (propertyName in unknownObject) {
console.log(unknownObject[propertyName as keyof typeof unknownObject]);
// Typechecks, but required explicit typecast
}
TS Playground link