Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 25, 2022 05:23 pm GMT

Typescript Series - Array Push Type

I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.

Let's create a type for the JavaScript Array.push function. Which takes pushes an element into the array in the last position.

Push<[1, 2], '3'> // [1, 2, '3']Push<['1', 2, '3'], boolean> // ['1', 2, '3', boolean]

So we know we have an array and our type should return an array + the new value.

type Push<TArray extends unknown[], U> = [...TArray, U]

TArray extends readonly unknown[] We first check our TArray is of type array.

then we simply spread the array and the new value into an array [...TArray, U]

Thank you!

you can find me here My Twitter


Original Link: https://dev.to/sarmunbustillo/typescript-series-array-includes-type-3pl4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To