Mutability 12 exercises
solution

Two Options for Improving Promise Return Types in TypeScript

As mentioned, there are two different solutions to this challenge.

Solution 1: Defining a Return Type

The first solution is to define a return type for the fetchData function.

Inside the Promise type, a tuple is defined with either Error or undefined as the first member, and an optiona

Loading solution

Transcript

00:00 Okay, the first solution here is to basically add a return type to the FetchData function. And to say, okay, we say promise inside here, and we inside the promise we have a tuple that either has error or undefined as the first one, and then in the second member it has any in the second one. So this is what the data is typed at, any.

00:19 And what we'll get here is error, is error or undefined, which is good, and data is any. This though is a little bit cumbersome as a type, and there's a really neat technique that you can use to make it work. You can say, instead of defining a return type, you can on each tuple here, you can

00:37 make it infer as const. So you add as const to each member of this tuple. So the first one, or sorry, not each member of the tuple, to each return value. So we first return a tuple with this error inside here, and the second one is we return its undefined as the error, and then the data inside here.

00:57 And so if we hover over fetch data, you'll notice that it kind of returns two possible tuples, either read-only error or read-only undefined any. So now error is inferred as error or undefined, and we have data any. Super nice. Like this is a really cool technique for when you're working, let's say, in React and you

01:16 want to return a custom hook with like two tuple members or something like that. It's such a nice little thing you can do. And of course, we don't need to have more than one of these. We could just have one down here, and now it would be just return to tuple with undefined and the result. Very, very nice little technique.

01:32 And as const again, coming up really like coming in very handy, just telling little parts of our application, no, don't make this an array, make it a const instead. Because if we don't have this, of course, then the return value is promise any array.

01:49 TypeScript doesn't know that this only contains two members of this array because it might think, oh, you might want to add things onto there. You might want to default it to something mutable because that's JavaScript's behavior. But just adding as const infers it as a tuple. Super cool.