2

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.

Nino Filiu
  • 10,020
  • 6
  • 40
  • 53
  • 1
    If you really want to do this with TypeScript, just use `foo['undefined']` then. As you've pointed out yourself, this is the same as `foo[undefined]`. – Rudey Aug 13 '20 at 10:29
  • 2
    They point to the same property because keys that are neither strings nor symbols are converted to strings. This is a fact of life in JavaScript and TypeScript wants you to be explicit since accidentally indexing with such a value is a source of bugs. If you actually want to have a key that _is_ the `undefined` value, you can must a `Map`. – Aluan Haddad Aug 13 '20 at 13:49

0 Answers0