Arsen Karapetjan
Arsen Karapetjan

Reputation: 113

typescript return object or array error

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

Answers (2)

Sefe
Sefe

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

Paleo
Paleo

Reputation: 23682

You can use overloads. An example:

type MyEvent = { evtName: string }
function abc(): MyEvent[]
function abc(param): MyEvent
function abc(param?): any {
    // do the stuff
}

abc().length // ok
abc()[0].evtName // ok
abc("def").evtName // ok

Upvotes: 3

Related Questions