Manipulation with elements of tuple type in TypeScript

Tuple elements manipulation examples
Tuple elements manipulation examples

Today we discuss Pop and other methods: Push, Shift and Unshift

We already practiced getting first element of tuples and last element of tuples

Let's apply our knowledge again 💪

Pop

Array.prototype.pop removes the last element of Array in JS.

Since TypeScript 4.2 we can use rest elements not only at the very last position of a tuple type.

We will infer all elements but the last and return them as result:

Pop solution
Pop solution

Push

Array.prototype.push adds the element to the end of Array in JS.

We spread all elements we have and add the pushed element to the end:

Push solution
Push solution

Shift

Array.prototype.shift removes the first element of Array in JS.

So we need to infer all elements but the first one and return them as result:

Shift solution
Shift solution

Unshift

Array.prototype.unshift adds the element to the beginning of Array in JS.

We spread all elements we have and add unshifted element to the beginning:

Unshift solution
Unshift solution

Summary

We just applied spread in different manipulations with tuples.

If you're interested with examples, please have a look at Playground

Have a good evening ☁️ and nice weekend 💃🕺!

typescript

Alexey Berezin

Senior Software Engineer, UK Global Talent 🇬🇧

The portrait photo of me

Thank you for reading my blog post! If you have any questions, suggestions, or just want to say hi, feel free to reach out in social networks, or via email. I would love to hear from you!

Comments