Home > OS >  How to map constants to strings
How to map constants to strings

Time:01-11

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

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

CodePudding user response:

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

  • Related