Home > Software engineering >  How to create a field type based on another field value?
How to create a field type based on another field value?

Time:03-25

I'm trying to write types for the following simplified example.
How can I tell Container that the config will be derived from the component?

type Container = {
  component: "A" | "B" | "C";
  config: AConfig | BConfig | CConfig;
}

type App = {
  containers: Container[];
}

I tried using generics, but then the containers in App cannot have multiple types.

type Config = {
  A: AConfig;
  B: BConfig;
  C: CConfig;
}

type Container<T extends keyof Config> = {
  component: T;
  config: Config[T];
}

type App<T> = {
  containers: Container<T>[];
}

CodePudding user response:

You need a mapped type to iterate over the keys of your Config type and create the pairing.

type ConfigContainer = {
    [K in keyof Config]: { component: K, config: Config[K] }
}[keyof Config]

This creates an object type that has all possible pairings as values, and then you index that object by it's own keys to get the value types as a union.

See Playground

  • Related