typescript-book
typescript-book copied to clipboard
Index signature code block #3 produces error
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.
Object keys should be number or string. Should NOT be an object.
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.
...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.
Just try foo[obj as string] = 'World'