Home > Enterprise >  Generate a type in Typescript that will have as many possible shapes that there are keys on another
Generate a type in Typescript that will have as many possible shapes that there are keys on another

Time:10-13

I have a typescript issue and i don't how to solve it. Here is my problem. I would like to generate a type that will have as many possible "shapes" that there are keys on another type. Let's me explain with a "real" case.

For example, I have this custom type :

interface MyFilters {
  min: number,
  max: number,
}

Of course, this custom type can have more than 2 properties that can be something other than number.

And from this MyFilters type, I would like to generate a type like this :

type Filter =
  | {
      name: "min";
      value: number; // typeof MyFilters["min"]
    }
  | {
      name: "max";
      value: number; // typeof MyFilters["max"]
    };

But the Filter type has to be generate in a generic way, like TFilter<MyFilters> and not explicitly as above.

I tried something like this :

interface MyFilters {
  min: number;
  max: number;
}

type TFilters<T, Key extends keyof T> = {
  name: Key;
  value: T[Key];
};

But with this solution, I have to specify the property name 2 times.

const minFilter: TFilters<MyFilters, "min"> = {
  name: "min",
  value: 0,
};

So I would like to known if it can be simplify like this :

// by removing "min" from generics
const minFilter: TFilters<MyFilters> = {
  name: "min",
  value: 0,
};

Thanks in advance for your helps.

CodePudding user response:

A mapped type will do this for you:

type TFilters<T> = {
  [K in keyof T]: {
    name: K;
    value: T[K];
  }
}[keyof T]

type Filters = TFilters<MyFilters>

Playground

  • Related