Essential Types And Notations 20 exercises

Tuples for Precise Array Structures in TypeScript

Here we have a setRange function that takes in an array of numbers:

const setRange = (range: Array<number>) => {
const x = range[0];
const y = range[1];
// Do something with x and y in here
// x and y should both be numbers!
type tests = [
Expect<Equal<typeof x, number>>, /

Loading exercise


00:00 Let's take a look at tuples in TypeScript. Here we have a setRange function and the setRange function takes in a range which is an array of numbers. We're grabbing x from the first member of range here, so from the 0 index, and then we're grabbing y from the 1 index, so the second element.

00:18 And we're expecting those to be of type number, but they're actually not. They're of type number or undefined. And here we have setRange, 0, 10, and this is good. But we're sort of like expecting it to... So we're getting an error from the second one where we're passing in a string,

00:36 but we're also not getting the right errors when we're not passing in the right number of members of the array. So here we've only passed one member of the array, but we're expecting to always pass in x and y. And here it's got too many members, so it's 0, 10, and 20, which is x, y, z, I guess.

00:54 But really, we just want x and y. So your job is to change this type annotation. This annotation is the problem. We want to change it to basically make TypeScript say we want a specific number of members in this array, which turns it into a tuple. So good luck.

01:12 We want to specify basically number and number kind of inside a tuple syntax, and your job is to find that syntax. Good luck.