Home > Software design >  Typescript accepts ENUM as a interface value but returns error when receive the props
Typescript accepts ENUM as a interface value but returns error when receive the props

Time:08-31

I created a UI library, to standardize things like sizes and colors, I created an ENUM to specify each value. enter image description here

And I passed this ENUM as a value in the props interface

enter image description here

So far everything working perfectly, in the storybook the values are perfectly set, and the library builds without problems.

enter image description here

But for some reason, when using the component as an installable dependency in the main application, when I set these values, an error appears in vscode.

enter image description here enter image description here

But even with this error in the middle of the screen, when I go to localhost:3000, the components are there perfectly, receiving the correct values and working normally

enter image description here

It's my first time using ENUM, does anyone know where I made the mistake and how can I fix it? Sorry for the amount of images, it was the best way to illustrate the error.

CodePudding user response:

Try exporting your enum as const:

export const enum sizes {
 small = "small",
 medium = "medium",
 large = "large"
}

CodePudding user response:

Since you are using TypeScript your VSCode tries to warn you that you are not using an enum for that attribute, you are using a string for that attribute.

You can avoid those warnings (and I recommend doing this for code maintainability) by doing this:

<Button color={colors.purple} size={sizes.small}>
    Test
</Button>

Also don't forget to import colors and sizes into your component. If in the future you change the properties on your enum, VSCode will warn you that the property has changed and is no longer supported.

Another thing, enums should be written in Pascal Case (similar to JAVA) to make them more easy to understand when reading code.

export enum Sizes {
 Small = "small",
 Medium = "medium",
 Large = "large"
}
  • Related