Home > OS >  Typescript strict boolean expression error
Typescript strict boolean expression error

Time:11-07

While creating conditional classes with the following lines of code:

className={({ selected }) =>
    classNames(
        selected
            ? 'bg-gray-100 text-gray-900'
            : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900',
        'group flex items-center px-2 py-2 text-base font-medium rounded-md'
    )
}

But I keep getting a Type '({ selected }: { selected: any; }) => string' is not assignable to type 'string'.ts(2322) error.

I have tried explicitly adding an any type but it didn't work.

Because I also integrated eslint to my project, I even tried adding a eslint-disable-next-line @typescript-eslint/strict-boolean-expressions rule just above the selected parameter, all to no avail.

Please can anyone figure out what I am doing wrong?

CodePudding user response:

What you're passing to the className prop is actually a function that takes a single argument, and then calls classNames to return a string. That's where this type is coming from:

({ selected }: { selected: any; }) => string

What you probably want to do instead is this (assuming that selected exists in scope):

className={
    classNames(
        selected
            ? 'bg-gray-100 text-gray-900'
            : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900',
        'group flex items-center px-2 py-2 text-base font-medium rounded-md'
    )
}

That will set the className prop to the result of calling classNames, which is what you want - a string.

  • Related