Reputation: 33
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 typeClassA[]
.
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
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
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