basarat / basarat/typescript-book

Index signature code block #3 produces error

Open
#239 4 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
21.6k
Forks
2.6k
PR merge metrics
No merged PRs in 30d

Description

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):
```typescript
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.

Contributor guide

Open the contributing guide

Research direction

Find the third example code block in the chapter on index signatures and reproduce it in the TypeScript Playground. Update the example or its explanation so the documented code matches current TypeScript behavior and no longer presents an unaddressed compiler error; verify the revised block in the Playground.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.