Discriminated Tuples in Custom Hooks
Here we have a useData
hook that returns a Result<T>
.
Result<T>
is defined as a tuple containing three different statuses: loading
, success
, and error
.
export type Result<T> = [ "loading" | "success" | "error", T | Error | undefined];
The useData
hook fetches data from
Transcript
00:00 In this exercise, we have a UseDataHook and the UseDataHook returns a ResultTee. ResultTee is defined as a tuple with three different statuses in there. And we've got Loading or Success or Error. And here it's defined as either Tee or Error or Undefined.
00:19 So this basically, what it does, it just fetches from a URL, then grabs the response, then sets it to SuccessData. So this result is sort of seemingly typed pretty well, except for the fact that when we go to use it, they're not sort of discriminating based on each other.
00:37 So here, Value is either Error or TitleString or Undefined, and Status is Loading or Error or Success. But what we can see here is that when we have this error here, we don't have an error defined as the value. When we've filtered out Loading and Error,
00:56 we don't have a kind of value.title here either. So this isn't right. Ideally, what we would like here is for these things to be grouped together. So your job is to work out what kind of other type of type signature we could define for this result in order to make this all work.
01:15 You shouldn't have to change anything in here, I don't think. It should just be a little change up here, and then you'll start to see it working. Good luck.