Search code examples
typescripttypes

Function that accepts a generic Type or an array of the same Type


  public treatment<Type>(input: Type | Type[]): Type {
    if (isArray(input)) {
      // input here is 100% Type[]
      return input.map((element) => treatment(element) /* <- this is telling Type 'Type[]' is not assignable to type 'Type'*/);
    }
    // input here is 100% Type
  }

The problem I'm facing is that IDE is complaining about the recursive call treatment(element) while I thought it should not. As in the other hand hovering on the variable inside the isArray check or after, gives the correct typing.


Solution

  • It you want to approach that either a single value or each value of an array should be treated, you can solve it like this:

    function treatEach<T, R>(input: T | T[], singleTreatment: (input: T) => R): R | R[] {
      if (input instanceof Array) {
        return input.map(singleTreatment);
      }
      let result: R = singleTreatment(input);
      return result;
    }
    

    input has got type T or T[] array. The function singleTreatment executes the treatment on an either the item or each item of the array.

    The function either returns a treated item of type R or an array of treated items of type R[].

    Sample call:

    let result: string[] | string = treatEach([1, 2, 3], i => i + "");