Remapping keys in type

Viewed 250

I want to create a type (U) that will be defined as having the keys of some given type T where T extends Object. The values of this new type will be defined as functions which will take in the value type for that key on the original type T and return the same type.

For instance if I had the type I1:

interface I1 {
  a: number;
  b: Date;
}

Then U<I1> would be equal to:

{
  a: (x: number) => number;
  b: (x: Date) => Date;
}

I did look at a few options with things like keyof, but I haven't yet figured out how best to do this. I tried, for instance:

export type U<T extends {}, K extends keyof T, V extends T[K]> = Record<K, (x: V) => V>;

But then you need to define explicit types for each of the generics. It seems like it's possible to remap keys in ts 4 with key remapping, but right now I'm stuck on 3.7.1.

Any thoughts on how this could be achieved?

1 Answers

I think something like this should work:

type U<T> = {
    [Prop in keyof T]: (x: T[Prop]) => T[Prop];
}

You can test it with:

type Test = U<I1>;

When you hover over Test you should see the desired signature.

Related