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

How to map constants to strings

I have a type definition like this

type Foo = {
    bold?: boolean,
    italic?: boolean,
    color: Colors <- this is the problem
}

Color has got to be one of these values

const col1= '#C62828'
const col2= '#01579B'
const col3 = '#E65100'

I thought I make an enum out of it

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

enum Colors {
    red: col1,
    blue: col2,
    orange: col3,
}

But this gives me

Only numeric enums can have computed members, but this expression has type ‘"#C62828"’. If you do not need exhaustiveness checks, consider using an object literal instead.

And then highlighlting col1, col2, col3.

What is the best way to create a mapping like this, so that I can use as a type for color? I want to make sure that

  1. only colors defined via col1, col2, col3 are allowed to passed and
  2. be able to use the actual value (i.e. #C62828) of the passed Color

>Solution :

You can use a constant with key value pairs for the colors.
Like:

const col1 = '#C62828'
const col2 = '#01579B'
const col3 = '#E65100'

const COLORS = {
    RED: col1,
    BLUE: col2,
    ORANGE: col3,
} as const // as const to type the values as (ex: '#C62828') instead of `string`.

For getting the values as types of the COLORS object use this type:

type Colors = typeof COLORS[keyof typeof COLORS] // "#C62828" | "#01579B" | "#E65100"

Now can implement the type to an Object and will only allow the values added to the COLORS constant.

type Foo = {
    bold?: boolean,
    italic?: boolean,
    color: Colors
}

const implementedFoo: Foo = {
    color: "#01579B"
}

const implementedFoo2: Foo = {
    color: COLORS.BLUE
}

Playground

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