OliverRadini
OliverRadini

Reputation: 6476

Typing a collection of merge functions for a given type

If I have a type such as:

interface ITest {
  a: number;
  b: string;
  c: boolean;
}

I would like to be able to generically define a type which can be a 'collection' of functions to merge a given property of the type.

I can define an individual 'Merger' something like:

type Merger<T, K extends keyof T> = (a: T[K], b: T[K]) => T[K];

But I'd look to be able to have a full collection of these such as:

const mergers: Mergers<ITest> = {
  a: (a: number, b: number) => a + b,   // should work with no error
  b: (a: string, b: number) => `${a}: ${b}`,    // this one should error
}

Can this be done?

Upvotes: 2

Views: 25

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250376

You just need to use a mapped type to map over the keys of T. You will even get contextual types for the parameters:


type Merger<T, K extends keyof T> = (a: T[K], b: T[K]) => T[K];
type Mergers<T> = {
  [P in keyof T]: Merger<T, P>
}

const mergers: Mergers<ITest> = {
  a: (a, b) => a + b,   // ok, contextualy typed a and b 
  b: (a: string, b: number) => `${a}: ${b}`,    // error
}

Playground Link

Upvotes: 3

Related Questions