typescript-book icon indicating copy to clipboard operation
typescript-book copied to clipboard

Index signature code block #3 produces error

Open DestyNova opened this issue 8 years ago • 4 comments

The third block of example code in the chapter on index signatures produces this error in the TypeScript Playground:

Type '{ toString(): string; }' cannot be used as an index type.

The code (original comments stripped for clarity):

let obj = {
  toString(){
    console.log('toString called')
    return 'Hello'
  }
}

let foo:any = {};
foo[obj] = 'World'; // ERROR
console.log(foo[obj]);
console.log(foo['Hello']);

I tried to figure out what this means and why it happens, but don't know enough about TypeScript yet. It seems that the compiler no longer assumes that toString should implicitly be called, even though the typechecker expects it to return a string.

DestyNova avatar Feb 27 '17 09:02 DestyNova

Object keys should be number or string. Should NOT be an object.

djyde avatar Feb 27 '17 10:02 djyde

That's what I thought. Actually I just noticed that a later code example is almost the same, yet explicitly states that there will be an error and that foo[obj.toString()] must be used instead.

I think the earlier example (from my first comment) should have its types removed, replace let with var, and make clear that it is plain Javascript, NOT TypeScript.

DestyNova avatar Feb 27 '17 10:02 DestyNova

...or, since TypeScript still emits Javascript even if the typechecker fails, at least add a comment to explain that this will produce an error, but that the resulting JS will still do what it says.

DestyNova avatar Feb 27 '17 10:02 DestyNova

Just try foo[obj as string] = 'World'

djyde avatar Feb 27 '17 14:02 djyde