Essential Types And Notations 20 exercises

Using Tuple Syntax in TypeScript

To specify a tuple in TypeScript, use square brackets with the types inside:

[number, number];

In this case, we would update the setRange function to use this syntax instead of the array syntax:

const setRange = (range: [number, number]) => {

Now we've

Loading solution


00:00 Okay, so the fix here instead of using this array syntax and as well this wouldn't work with number like this We have to use the tuple syntax and the tuple syntax looks like this Inside the square brackets you actually say number comma number

00:16 And now what's happening here is we've specified a type that is a tuple an array with two Members this means that if we pass it to few arguments Then it's going to say argument of type number is not assignable to parameter of type number number source has one element

00:34 But target the thing that we're trying to assign to requires two So this is really really useful there's even another syntax for this too if you want to just give these tuples a bit more clarity as to what the Members of the tuple are intending you can actually give them little annotations little names

00:52 So the first one now is typed as X and the second one is typed as Y And this means then that when you're calling the tuple you can actually see them inside there Which means that you don't get confused between between Y and X or if these two were to represent width and height Then they would be a sort of disambiguated. You'd understand them easier

01:11 So this is a really really nice way that you can express Arrays of fixed length in TypeScript and it's really cool to have this as a first-class sort of thing you can do in TypeScript