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

What does this TypeScript mean with regards to useEffect?

I am new to TypeScript and am learning it by setting up a new project and how I would normally do that, but with TypeScript along the way. I have this bit of React working but do not know what this means — therefore which document I should be reading to learn up on it.

const [user, setUser] = useState<any | null>(false);

Specifically the <any | null> part. This is the only new part with TypeScript but not sure how to read this. Is this saying the type is any type, else null? What are some other options I can use in place of any and null? Are there scenarios I should avoid?

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

>Solution :

That’s the correct way to type a useState but normally you want to avoid using any.

In your example you are creating some state with a default value of false. In this case you don’t really need to define the type as it will be inferred as a boolean. Let’s say that value could be null or an object, then you could define the type like so:

// Just an example
interface User {
  username: string
}

const [user, setUser] = useState<User | null>(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