Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Set types of object values

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading