Home > Net >  NextJS TypeScript How to define Enum for strings
NextJS TypeScript How to define Enum for strings

Time:12-07

In my nextjs-app I have a component, which has a prop of the type string. Now I want to define an enum, so I tried to do this:

enum Label {
 dermatology = 'Dermatologi',
 psychology = 'Psykologi',
 rheumatology = 'Reumatologi',
 physiology = 'Fysiologi',

}

interface ISpecialist {
  label?: Label
}

export default function Specialist({ specialist }: { specialist: ISpecialist }) {
   return (
      <div>
        <span>{specialist.label === Label}
      </div>
   )
}

but this doesn't work - can someone help me out?

the prop label is as mentioned before of the type string and the values are for example 'psychology' or 'dermatology'

CodePudding user response:

If you want to print the corresponding value of the enum, access it like the enum key.

    <span>{Label[specialist.label] }

CodePudding user response:

In your code, you are trying to compare the label prop to the Label enum itself, which is not valid. To compare the label prop to a specific value in the Label enum, you need to use the dot notation to refer to the value you want to compare against. For example, you can use the following code to compare the label prop to the Dermatology value in the Label enum:

<span>{specialist.label === Label.dermatology}</span>
  • Related