Vincent J
Vincent J

Reputation: 801

Typing recursive function with union return type in typescript

I am trying to type a typescript function who adds a property to objects in nested arrays of arbitrary depth. The runtime code is trivial in Javascript but i have been pulling my hair for the whole day to get the Typescript types to compile.

The code should take an array like this [{}, {}] or this [[{},{}]] or this [[[{},{}]]] and add the marked:true property to every object;

type Nested<T> = T | Array<Nested<T>>;
function markNested<T>(objOrNestedArray: Nested<T>): T {
  if (Array.isArray(objOrNestedArray)) {
    return objOrNestedArray.map(markNested);
  } else {
    return { ...objOrNestedArray, marked: true };
  }
}

Thank you.

Upvotes: 1

Views: 666

Answers (1)

Daniel Gimenez
Daniel Gimenez

Reputation: 20524

You were just missing the correct return type on the function. It needed to be Nested<T> like the source array. For completeness, I also added the marked property, since that might be useful to look up.

function markNested<T>(objOrNestedArray: Nested<T>): Nested<T & { marked: boolean }> {
  /*... */
}

Upvotes: 1

Related Questions