TypeScript object bracket notation
TypeScript has a long-standing bug related to object bracket notation.
Let’s say we have the following object:
const example = { one: 'uno', two: 'dos', three: 'tres' }
We can access the properties of example
using either dot notation or bracket notation:
console.log(example.one.toUpperCase())
console.log(example['one'].toUpperCase())
const key = 'one'
console.log(example[key].toUpperCase())
TypeScript is smart enough to understand all of the above examples.
However, it will throw an error1 for the following code, even though we first check whether the property exists on the example
object:
const getProperty = (prop: string) => {
return prop in example ? example[prop] : ''
}
console.log(getProperty('one'))
The only workaround is to explicitly suppress the error, using the @ts-ignore
directive.
const getProperty = (prop: string) => {
if (prop in example) {
// @ts-ignore
return example[prop]
}
return ''
}
Footnotes
-
Assuming the
--noImplicitAny
compiler flag istrue
. ↩
Sign up for my newsletter
A monthly round-up of blog posts, projects, and internet oddments.