TypeScript Question

Strange indexable styping

Typescript (2.0) doesn't give an error on this:

let x: { [index: string]: Object } = {1: 2}

I see there two potential errors:

  1. Index field is number type but should be string

  2. item type is number too but should be an Object type

Why does it passes?

Answer Source
  1. In the Indexable Types docs it's noted that:

There are two types of supported index signatures: string and number. It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, JavaScript will actually convert that to a string before indexing into an object. That means that indexing with 100 (a number) is the same thing as indexing with "100" (a string), so the two need to be consistent.

Which is why it accepts it when you use a number as an index instead of a string.
Indexes are always strings.

  1. In the part in the docs where Any is explained it's noted that:

... variables of type Object only allow you to assign any value to them ...

With the following example:

let prettySure: Object = 4;

Basically, Object can be anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download