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

Time:11-17

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

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

screenshot

enter image description here

CodePudding user response:

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.

  • Related