An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
August 25, 2022 05:23 pm GMT
Original Link: https://dev.to/sarmunbustillo/typescript-series-array-includes-type-3pl4
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To