Typing a useState

Hello, I am having some minor problems with a small thing.

On my playground below I make the compiler understand what I want to do with the following line

      | Loaded(asd: user) =>

but I would prefer if I could add a type already when I create the state

    let (user, setUser) = React.useState(_ => Loading)

Is it possible to add something to “Loading” there so that it knows that eventually it will be a user? It’s a small thing but the compiler somehow thinks I am passing a formstate even though the fullName is different from fullname and that it is a loadable type which formstate never is.

Playground to where you can see my code. Thanks in advance.

There’s a few different ways to approach it, but the simplest in your example would be to type the return type of the useState function:

let (user, setUser) = React.useState((_): loadable<user, 'a> => Loading)
1 Like

Thanks, exactly what I wanted!

1 Like

you can also annotate in the tuple:

let (user: loadable<user, 'e>, setUser) = React.useState(_ => Loading)

Might be a bit more idiomatic.

2 Likes

Btw, using useReducer is much more joyful in ReScript IMHO

3 Likes