My goal is to create a type that ensures the correct usage of the DynamicColor
type.
enum ColorsEnum {
red = "red",
green = "green",
blue = "blue",
yellow = "yellow",
}
type ColorsMapperType = {
type: ColorsEnum
red: {
redProperty: string
}
green: {
greenProperty: string
}
blue: {
blueProperty: string
}
yellow: {
yellowProperty: string
}
}
type ColorsMapper = Omit<ColorsMapperType, "type">
export type DynamicColor = {
[ColorType in keyof ColorsMapper]: {
[Prop in 'type' | ColorType]: Prop extends 'type' ? ColorType : ColorsMapper[ColorType]
}
}[keyof ColorsMapper]
Codesandbox: https://codesandbox.io/s/naughty-sanderson-niqez?file=/src/index.ts
I have managed to make it mostly functional. However, I want the type
field within the DynamicColor
type to be of the correct ColorEnum
type.
Currently, I receive autocomplete suggestions for the string values of ColorEnum
, rather than the actual enum type.
For instance, the following code should be considered valid:
const color: DynamicColor = {
type: ColorsEnum.green,
green: {
greenProperty: "1",
},
}
On the other hand, none of the following pieces of code should pass validation:
const color0: DynamicColor = {
type: "green", // invalid because it doesn't match the ColorsEnum type
green: {
greenProperty: "1",
},
}
const color1: DynamicColor = {
type: ColorsEnum.blue, // invalid because the property "blue" is missing
}
const color2: DynamicColor = {
type: ColorsEnum.blue, // invalid because the color property does not align with the correct type (ColorsEnum.blue requires a "blue" property)
green: {
greenProperty: "1",
}
}
const color3: DynamicColor = {
type: ColorsEnum.blue, // invalid due to having more than one color property
blue: {
blueProperty: "1",
}
green: {
greenProperty: "1",
}
}
Is there a method to achieve this? Thank you in advance, and any suggestions for enhancing this code are welcome.