Search code examples
reactjstypescriptreact-typescript

React + Typescript: An expression of type 'void' cannot be tested for truthiness


I have this react component:

import { useState } from "react";

interface itemProps {
  item: {
    id: number;
    name: string;
    description: string;
    links: {
      id: number;
      link: string;
    }[];
    tecs: string[];
    imgs: string[];
  };
  setModalVisible(arg: boolean): void;
  setSrc(src: string): void;
}

export const WorkComponent = ({ item, setModalVisible, setSrc }: itemProps) => {
  const [active, setActive] = useState<boolean>(false);

  const number = (id: number) => {
    return id < 10 ? `0${id}` : id;
  };

  return (
    <div className="work">
      <div
        className="container"
        onMouseOver={() => setActive(true)}
        onMouseOut={() => setActive(false)}
      >
        <h2>
          <span>{number(item.id)}.</span>
          {item.name}
        </h2>
        <p>{item.description}</p>
        <p className="tecs">{item.tecs.join(", ")}</p>
        <div className={`images ${active ? `active` : ``}`}>
          {item.imgs.map((item, index) => {
            let img = item;
            return (
              <div
                className="img"
                key={index}
                style={{ backgroundImage: `url(/imgs/${img})` }}
                onClick={() => setModalVisible(true) || setSrc(`/imgs/${img}`)}
              ></div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

I have an issue on the onClick function. Typescript says that "An expression of type 'void' cannot be tested for truthiness" with setModalVisible(true).

How can i solve this issue? i've tried to change the setModalVisible(arg: boolean): void; to setModalVisible(arg: boolean): boolean;but this shows me another error.


Solution

  • onClick={() => {
        setModalVisible(true);
        setSrc(`/imgs/${img}`);
    }}
    
    

    Instead of using the logical OR (||), you have to make separate function calls inside the onClick handler.