2

I have a type which looks like this

export type Theme = | 'primary'
    | 'secondary'
    | 'success'
    | 'danger'
    | 'warning'
    | 'info'
    | 'dark'
    | 'light'

Now, i am creating a mapping where I want the keys be same as the ones in the theme, So i tried this but this keeps on throwing following error

const colorMapping: { [key: Theme]: string } = {
    primary: '#0275d8',
    success: '#5cb85c'
}

An index signature parameter type cannot be a union type. Consider using a mapped object type instead

Can someone please help me in figuring out how I can fix this error?

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 1
    This question is a duplicate of [this one](https://stackoverflow.com/questions/54438012/an-index-signature-parameter-type-cannot-be-a-union-type-consider-using-a-mappe) or maybe [this one](https://stackoverflow.com/questions/62525903/require-specific-string-as-optional-key-in-typescript-interface) – jcalz Aug 24 '20 at 03:47

1 Answers1

3

As suggested by the error message, use a mapped type:

export type Theme = 'primary'
    | 'secondary'
    | 'success'
    | 'danger'
    | 'warning'
    | 'info'
    | 'dark'
    | 'light';

const colorMapping: { [key in Theme]?: string } = {
    primary: '#0275d8',
    success: '#5cb85c'
};
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156