typescript-book
typescript-book copied to clipboard
Mapped types mistaken for index signature type
Hi @basarat!
I believe the chapter on index signature types may contain some slightly misleading information, although I could be wrong.
In the section title Using a limited set of string literals, the example uses mapped types, which are a separate feature from index signature types.
As far as I understand, index signatures define types for all key lookups, whereas mapped types are a tool for programmatically creating interfaces with only known keys.
It took me awhile to understand the difference myself, especially as the syntax are so similar for the two:
// Index signature
{ [index: string]: string }
// Mapped type
{ [key in 'foo']: string }
// … generates:
{ foo: string }
// The generated type has no index signature
Index signatures are useful for creating dictionaries aka maps, and mapped types are useful for creating records. https://gist.github.com/OliverJAsh/2a538639e35db183b0cc16ca8ab520a7
What do you think? My only concern is that mapped types are referred to as index signatures in this chapter, but as you can see from the example above, a mapped type does not generate a type with an index signature. They are different tools. 🤔
a mapped type does not generate a type with an index signature
Limited set of strings is not an index signature, but a common question on stackoverflow (the origin of me adding this and most other things in the book). I've added a quick fix to make clear the feature name. Will work more on it later :rose: