My question is not about the meaning of the meaning of the
Type 'undefined' cannot be used as an index type
typescript error, as in this question and this one - I know that it happens when doing someObject[someValueThatMightBeUndefined]
.
Rather, I want to know why TypeScript prevents this, as undefined
can be used to index objects:
const foo = {}
foo[undefined] = 10
foo[undefined] // 10
My best guess is that using undefined
as a key is a bad idea because undefined
and 'undefined'
are not the same, yet these
foo[undefined]
foo['undefined']
foo.undefined
point to the same property. But I'm not entirely satisfied with this answer because TypeScript should prevent code that breaks, not bad code.