reusing index in indexable types

In indexable types, we can reuse the index for value types as well. This is very handy. For example, below we have interfaces Foo and Bar. Type BarToFooMap defines mapping from Bar to Foo. With indexable types and keyof we can ensure the mapped values are of correct type:

interface Foo {
  a: string
  b: number
}

interface Bar {}

type BarToFooMap = {
  [k in keyof Foo]: (bar: Bar) => Foo[k] // <-- 🎉 using index type k in value type
}

const barToFooBroken: BarToFooMap = {
  a: () => "hello",
  b: () => "world", // 🎉 compilation error: improper return type for b
}

const barToFooFixed: BarToFooMap = {
  a: () => "hello",
  b: () => 1, // this compiles 🎉
}

Would you like to connect? Subscribe via email or RSS , or follow me on Twitter!