hand sketched logo of electrons orbiting a nucleus

TIL: Immediately Indexed Mapped Type

Pretty sure Matt Pocock named this pattern.

Example with a record type:

type Foo = {
  a: string;
  b: number;
  c: boolean;
};

/**
 * | {
 *   key: "a";
 *   value: string;
 * }
 * | {
 *   key: "b";
 *   value: number;
 * }
 * | etc...
 */

type FooMapped = {
  [K in keyof Foo]: { key: K; value: Foo[K] };
}[keyof Foo];

We can use this to map union types as well:

type Foo = 'a' | 'b' | 'c';

/**
 * | {
 *   key: "a";
 *   value: "a";
 * }
 * | {
 *   key: "b";
 *   value: "b";
 * }
 * | etc...
 */

type FooMapped = {
  [K in Foo]: { key: K; value: K };
}[Foo];

References

TIL: Distributive Conditional Types

🤓 Today I Learned,

TypeScript

This is such a simple union example that we could have done this same thing with an IIMT:

TIL: React.ElementType includes intrinsic and custom types

React,

🤓 Today I Learned,

TypeScript

This is an example of the IIMT pattern and captures all the intrinsic elements in JSX.