DEV Community

Discussion on: What's going on with index types in TypeScript?

Collapse
 
macsikora profile image
Pragmatic Maciej

We have here three separated things.

1.Index type
Its a type accessor by index. So for example User['id'] take a type of property id from User type.
More about index type
2.Index signature type
Its a way to define the type, but limited to index type being string or number. More about that - index signatures

// Indexed type syntax only available for keys being string or number
type Donk = {
  [keya: string]: string;
   // no more rows available
}
const donk = { 'any_str': 'any_str' }; // string to string object
Enter fullscreen mode Exit fullscreen mode

3.Mapped types
Mapped type is a construction allows create a type by mapping through keys being another type. This is exactly the construct which allows on creating object types with specified keys and values types.

Mapped type example:

type Keys = 'a' | 'b' | 'c'
type Donky = {
   [K in Keys]: string
}
const donky: Donky = { a: 'a', b: 'b', c:'c' }; // a | b | c to string object
Enter fullscreen mode Exit fullscreen mode

More about mapped type