Hone logo
Hone
Problems

TypeScript Array Element Type Inference

This challenge focuses on understanding and effectively utilizing TypeScript's capabilities for defining and inferring the types of elements within arrays. Mastering this is crucial for building robust and maintainable JavaScript applications with TypeScript, ensuring data integrity and catching potential errors early in the development process.

Problem Description

Your task is to implement a TypeScript function that processes an array of numbers and returns a new array containing only the even numbers from the original array. You will need to correctly define the type for the input array and the output array, leveraging TypeScript's generic and type inference features.

Key Requirements:

  1. Function Signature: Create a function named filterEvenNumbers that accepts a single argument: an array of numbers.
  2. Type Definition: The input array should be explicitly typed as an array of numbers. The function should return a new array, also typed as an array of numbers.
  3. Filtering Logic: The function should iterate through the input array and return a new array containing only those elements that are divisible by 2 (i.e., even numbers).
  4. No Mutation: The original input array must not be modified.

Expected Behavior:

The function should accurately filter out odd numbers and preserve the order of even numbers from the original array.

Edge Cases to Consider:

  • An empty input array.
  • An input array containing only odd numbers.
  • An input array containing only even numbers.

Examples

Example 1:

Input: [1, 2, 3, 4, 5, 6]
Output: [2, 4, 6]
Explanation: The function correctly identifies and returns the even numbers from the input array.

Example 2:

Input: [7, 9, 11, 13]
Output: []
Explanation: The input array contains only odd numbers, so the resulting array is empty.

Example 3:

Input: []
Output: []
Explanation: An empty input array results in an empty output array.

Constraints

  • The input will always be an array.
  • The elements of the input array will always be numbers.
  • The function should have a time complexity of O(n), where n is the number of elements in the input array, as it needs to iterate through the array once.

Notes

Consider how you can explicitly type the function's parameters and return value. Think about the benefits of using TypeScript's built-in array types. You do not need to use generics for this specific problem, but be aware of how they can be used to create more flexible array processing functions in general. The core is to demonstrate understanding of basic array typing.

Loading editor...
typescript