Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem setting useState with TypeScript to display data in an error modal-React.js

I pass my React.js application on TypeScript.
My ErrorModal component only displays when the error state contains "title" and "message" properties. The default state is false.
Like this, if there are the properties the error modal is displayed.

interface Error {
    title: string;
    message:string;
  }

  const [error, setError] = useState<boolean | Error>(false);

The problem is that typescript tells me error.title is badly defined. I created interface Error with title and message but TS underlines them.

I don’t see how to solve this problem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{error && (
        <ErrorModal
          title={error.title}
          message={error.message}
          onConfirm={() => setError(false)}
        />
      )}

screenshot

enter image description here

>Solution :

TS does not know what type it is. So you have to explictly check the type before it can understand what type it is. This concept is called narrowing (read more here typescriptlang.org/docs/handbook/2/narrowing.html ) .

A solution could be:

{error && typeof error != "boolean" && (
        <ErrorModal
          title={error.title}
          message={error.message}
          onConfirm={() => setError(false)}
        />
      )}

I think it should work, but i think an easier solution would be to not use a union type and just use Error as a type . When there are no errors then it could be null.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading