Search code examples
reactjstypescriptstorybook

How can I solve problem with typescript and @storybook/addon-knobs


I want to use @storybook/addon-knobs method text. I set this type in my code type ButtonColor = 'primary' | 'transparent' | 'light' and I wanna write text in input (text from addon):

const ButtonStories = () => (
  <Button
    borderRadius={16}
    color={text('color', 'primary')}
  >
    {text('value', 'Button')}
  </Button>
)

But when I use it I get as error:

Type 'string' is not assignable to type 'primary' | 'light' | 'transparent' | undefined

How can I fix it?


Solution

  • The problem is that text does indeed return a string nothing is constraining the user from entering any value you can however use a radio component instead.

    // Change ButtonColor where it's defined
    enum ButtonColor { primary = 'primary', transparent = 'transparent', light = 'light' }
    
    // use enum values as Array.
    const ButtonColors = Object.keys(ButtonColor)
    
    // Or redefine all values as an array
    // const ButtonColors = ['primary', 'transparent', 'light']
    
    const ButtonStories = () => (
      <Button
        borderRadius={16}
        color={radio('color', ButtonColors, ButtonColor.primary)}
      >
        {text('value', 'Button')}
      </Button>
    )