'How to create a field type based on another field value?
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>[];
}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
