How do you use a fallback class for clsx to prevent Typescript complaining?

65 views Asked by At

I have a basic spinner component that accepts a string props for size. I'm conditionally applying the size, however I still get the following type error on the size prop

Type 'string' is not assignable to type '"sm" | "md" | "lg" | "xl" | undefined'.ts(2322)

I would have thought adding a static value like 'md' into the size prop would fix this, but it doesn't. What am I missing?

<LoadingSpinner
    color={spinnerColor}
    size={clsx(
      size === 'sm' && 'sm',
      size === 'md' && 'sm',
      size === 'lg' && 'md',
    )}
  />
1

There are 1 answers

0
Jonas Beck On

You can use enum from the warning above when declaring a value for it. for example:

type MySize = "sm" | "md" | "lg" | "xl";
const [size, setSize] = useState<MySize>();

then typescript will force you use one of them when settting size. Hope this helps you.