Manipulation with Tuple elements

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

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

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

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

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 ๐Ÿ’ƒ๐Ÿ•บ!

typescriptmedium

Let's chat and have fun ๐Ÿง‘โ€๐Ÿ’ป๐Ÿ‘ฉโ€๐Ÿ’ป

No more often than once a week I write ๐Ÿ“„ about TypeScript ๐Ÿ’ช, video playback ๐Ÿ“บ and frontend related topics. You can unsubscribe in any time โ†˜๏ธ

ยฉ 2021, Built with Gatsby