How to map the select control options with the certain type?

1.4k views Asked by At

In TypeScript I have a certain type of the values called

export type Align = 'start' | 'end' | 'center';

For the Component Story I would like to make one prop interactive for the user, for this I am adding a select control to the panel, is there a way to list options by referring to the type Align rather than copypasting the values ?

SomeStory.argTypes = {
 align: {
  control: 'select',
  options: ???,
  // options: ['start' , 'end' , 'center']
  } 
};
2

There are 2 answers

0
Nick Vu On

You cannot convert a type to an array of values, but you can achieve it in the opposite way

const options = ['start' , 'end' , 'center'] as const;
type Align = typeof options[number]; //'start' | 'end' | 'center'

SomeStory.argTypes = {
 align: {
  control: 'select',
  options: options,
  } 
};

Playground

0
Amaan Kulshreshtha On

You can leverage VSCode's intellisense in this case

const options = [/* if you use the intellisense here, 
it will pick up the strings from the union type */] as Align[];

SomeStory.argTypes = {
 align: {
    control: 'select',
    options
  } 
};