Reputation: 113
Hello i write application on Angular2 and Typescript and create service for get event. I guess what my function return array events, when i not pass arguments in function and return Object when have arguments.
But in my component lintner show error for this construction.
this.event.length
Type 'Event | Event[]' is not assignable to type 'Event[]'. Type 'Event' is not assignable to type 'Event[]'. Property 'length' is missing in type 'Event'.
Can i catch this error? Because i know what in this component get Array of Events
Upvotes: 0
Views: 3615
Reputation: 14007
The error message is self-explanatory: an Element | Element[]
is not an Element[]
(the opposite is true, but that is not what you're doing). You can use a type guard to narrow down the union type:
function isElement(value: Element | Element[]) value is Element {
return value instanceof Element;
}
function functionWithReturn(): Element | Element[] {
//Do something
}
function functionWithParameter(value: Element[]) {
//Do something
}
function doWork() {
let value = functionWithReturn();
if (!isElement(value)) {
functionWithParameter(value);
}
}
Upvotes: 1