Sobes.tech
Junior — Senior

Correct typing of the map function in TypeScript

livecode

Task condition

Task: write types for a map function that takes an array of elements of one type and a transformer function, and returns a new array filled with elements of another type.

Requirements:

  • The function should accept two parameters: source — an array of elements of type TSource and converter — a function that transforms an element of TSource into TResult.
  • The return value should be an array of elements of type TResult.
  • Types should be generic so that the compiler correctly infers types when calling the function.

Example usage (code remains unchanged):

const numbers = [1, 2, 3];
const strings = map(numbers, n => n.toString()); // type of strings: string[]