I have object with colors:
const colorNamesToRgb: ColorNamesToRgb = {
red: 'rgb(255, 0, 0)',
green: 'rgb(0, 255, 0)',
blue: 'rgb(0, 0, 255)',
yellow: 'rgb(255, 255, 0)',
};
And type for it (all values should be of Rgb type):
type Rgb = `rgb(${number},${number},${number})`
type ColorNamesToRgb = {
[key: string]: Rgb
}
But the problem now is that all of the keys of colorNamesToRgb object can be any strings.
But i have a function (it’s useless, but it’s just for example simplicity):
type ColorName = keyof typeof colorNamesToRgb
// can accept any string, no code completion
const getRgbByName = (colorName: ColorName) => {
return colorNamesToRgb.colorName
}
Is there way to do both,make all values be of type Rgb, and keys type be any of keys present on object? Without doing circular references.
Is it possible to do so without duplicating color names?
My goal is to get ColorName type, which is any key of object
>Solution :
You could use satisfies instead of explicitly giving a type to colorNamesToRgb.
const colorNamesToRgb = {
red: 'rgb(255, 0, 0)',
green: 'rgb(0, 255, 0)',
blue: 'rgb(0, 0, 255)',
yellow: 'rgb(255, 255, 0)',
} satisfies Record<string, Rgb>;
// ensures that the structure of the value matches, without changing its type
type Rgb = `rgb(${number},${number},${number})`;
type ColorName = keyof typeof colorNamesToRgb;
const getRgbByName = (colorName: ColorName) => colorNamesToRgb[colorName];