0

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?

0

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.