Hone logo
Hone
Problems

Implementing a Type-Safe Push Function in TypeScript

Many programming languages provide a push operation to add elements to the end of a list or array. In TypeScript, while arrays have a built-in push method, it's often beneficial to create custom, type-safe utility functions that can handle different collection types or enforce specific behaviors. This challenge asks you to implement a generic push function that can add an element to an array while ensuring type safety and returning the modified array.

Problem Description

Your task is to create a TypeScript function named push that takes two arguments:

  1. arr: An array of elements of type T.
  2. element: An element of type T to be added to the array.

The push function should:

  • Append the element to the end of the arr.
  • Return the modified arr.
  • Be generic, meaning it should work with arrays of any type (T).
  • Maintain type safety: the element being pushed must be compatible with the type of elements already in the arr.

You should not use the built-in Array.prototype.push method directly within your custom push function. Instead, explore alternative ways to achieve the same outcome while demonstrating your understanding of array manipulation and TypeScript generics.

Examples

Example 1:

const numbers = [1, 2, 3];
const newNumbers = push(numbers, 4);
// newNumbers should be [1, 2, 3, 4]
// typeof newNumbers should be number[]

Explanation: Pushing the number 4 onto the numbers array results in a new array [1, 2, 3, 4]. The type of the returned array remains number[].

Example 2:

const strings = ["apple", "banana"];
const newStrings = push(strings, "cherry");
// newStrings should be ["apple", "banana", "cherry"]
// typeof newStrings should be string[]

Explanation: Pushing the string "cherry" onto the strings array results in ["apple", "banana", "cherry"]. The type of the returned array is string[].

Example 3:

const mixedArray: (string | number)[] = ["hello", 123];
const newMixedArray = push(mixedArray, "world");
// newMixedArray should be ["hello", 123, "world"]
// typeof newMixedArray should be (string | number)[]

Explanation: Demonstrating the generic nature, pushing a string onto an array of string | number works as expected, maintaining the union type.

Constraints

  • Your push function must be a standalone function, not a method of a class.
  • You are forbidden from using Array.prototype.push within your push function.
  • The function should be generic (<T>).
  • The function must return the modified array.

Notes

Consider how you might create a new array that includes all elements from the original array plus the new element. Spread syntax (...) or other array construction methods might be useful here. The goal is to implement the logic of pushing an element, not just to wrap the existing method.

Loading editor...
typescript