Using TypeScript literal type, I'm able to ensure that the object values are made of a Color
and the string -primary
.
type Color = "green" | "blue" | "orange" | "red" | "purple" | "pink";
type ColorObject<Key extends string = Color> = Record<Key, `${Key}-primary`>;
const COLORS: ColorObject = {
green: "green-primary",
blue: "blue-primary",
orange: "orange-primary",
red: "red-primary",
purple: "purple-primary",
pink: "pink-primary"
};
But I would like to ensure that the value is the same as the key, i.e:
pink: "pink-primary" // good
pink: "red-primary" // bad
I searched quite a lot, not sure it's possible as the time I write this... Any ideas?
You should use mapped types to achieve it. In your current implementation, your type allows any string color to have any of the colors in the value. Instead by using mapped typed we will map through the colors separately and assign the corresponding value to them:
type Color = 'green' | 'blue' | 'orange' | 'red' | 'purple' | 'pink';
type ColorObject<Key extends string = Color> = {
[K in Key]: `${K}-primary`;
};
const COLORS: ColorObject = {
green: 'green-primary',
blue: 'orange-primary', // expected error
orange: 'orange-primary',
red: 'red-primary',
purple: 'purple-primary',
pink: 'pink-primary',
};