Wocha
Wocha

Reputation: 33

How to set array union as function return type

I have function parameter that takes in array union such as: (ClassA|ClassB)[].
How to return from a function, either ClassA[] or ClassB[]?

When I try to return type (ClassA|ClassB)[] I get the following error:

Assigned expression type (ClassA|ClassB)[] is not assignable to type ClassA[].

classA: ClassA[];
classB: ClassB[];

this.classA = this.function(this.classA, classAObject);
this.classB = this.function(this.classB, classBObject);

function(array: (ClassA|ClassB)[], item: ClassA|ClassB): any {
   // some code...
   return array;
}

Upvotes: 0

Views: 49

Answers (2)

Colliot
Colliot

Reputation: 1551

Function overloading can get you the desired type signature:

class A {
  a() {}
}
class B {
  b() {}
}

const a = new A();
const b = new B();

const arrayOfA: A[] = [];
const arrayOfB: B[] = [];

function doSomething(array: A[], item: A): A[];
function doSomething(array: B[], item: B): B[];
function doSomething(array: A[] | B[],item: A | B): A[] | B[] {
  return array;
}

const resultOfA = doSomething(arrayOfA, a);
const resultOfB = doSomething(arrayOfB, b);

You can check that resultOfA is deduced to be of type A[], and resultOfB of type B[], respectively.

Upvotes: 0

bryan60
bryan60

Reputation: 29335

array: ClassA[]|ClassB[]

type it like that if it's either an array of ClassA OR an array of ClassB. not an array of items that may be ClassA or ClassB

Upvotes: 1

Related Questions