Type Helpers 9 exercises
solution

Enforce a Minimum Array Length in a Type Helper

The first step to solving this challenge is to update ``NonEmptyArrayto acceptT. Since we are working with arrays, we can replace unknownwith an array ofT`:


type NonEmptyArray<T> = Array<T>;

This will still accept arrays with a length of zero, so there's more work to be done.

In

Loading solution

Transcript

0:01 In order to solve this, we need to take this and add a T to it. That's the first step. We need to add a type argument. The second step here is if we add, for instance, Array T here, then this is going to make the first steps of this happy.

0:16 What we're saying here is we're saying, "We have a NonEmptyArray and this is just now going to represent an array," except it's erroring here, because it accepts an array of zero length, which is not good.

0:29 The way to do this is we could specify this with a tuple. We can actually add T, T, T, whatever we wanted to here. This would force us to represent an array with three members in.

0:42 If we had const example is NonEmptyArray with a T here. In fact, let me say number. Then, it would make us go one, two, three.

0:52 It would actually error if we try to add a fourth one here, because source has four elements, but target only allows three.

1:00 The way to do this then is, the way to say at least one is, if you think about this in JavaScript, in fact function arguments even, you can use a rest parameter here.

1:10 You can say, T Array or Array T. Let's use this syntax. What this is doing is it's saying, "OK, you have to have one element in this array, but then the rest of the array could be as long as you want or as short as you want."

1:28 That means that you have to pass in at least one, but if you pass in one, it will be fine. If you want to make this like, you have to pass in at least two, then we would say T, T. Pass in at least three, like this for instance. You get the idea.

1:41 This is a really nice little bit of syntax to process these different types of arrays. This is used in the library zod, for instance, and this is one that you may find is really helpful for application code as well. This TypeHelper has a lot of different use cases.