Representing Palette
as a single non-generic interface
is not possible, but you can create a union of each desired combination of colorType
and color
:
type Palette = {
colorType: "light";
color: "EC3333" | "E91515";
} | {
colorType: "dark";
color: "#100F0F" | "140F0F";
}
To automatically generate this union type from Colors
, you can map over the keys of Colors
and then immediately index into the resulting mapped object type:
type Palette = { [K in keyof Colors]: {
colorType: K
color: Colors[K]
} }[keyof Colors];
By using IntelliSense, you can verify that this results in the same type as before, with the added benefit of automatic updates if Colors
change.
With this union type, you can now use Palette
and ensure that the constraints are enforced and understood:
const badPalette: Palette = {
colorType: "dark",
color: "E91515"
} // error!
const goodPalette: Palette = {
colorType: "dark",
color: "140F0F"
} // okay
Playground link to code