Carlinhos
Carlinhos

Reputation: 970

Return void or any other type with Typescript

Can i do this ? its possible ? If no, has an alternative method to do this ?

ngOnInit():  void | Observable<TModel> {
//return bla bla bla 
}

Upvotes: 0

Views: 4253

Answers (1)

David Sherret
David Sherret

Reputation: 106650

Yes, it's possible.

An alternative is to have a return type of Observable<TModel> | undefined, which will work well with strict null checks:

function myFunction(): string | undefined {
    return Math.random() < 0.5 ? "" : undefined;
}

const myString = myFunction();
myString.charAt(0);  // error
myString!.charAt(0); // ok

if (typeof myString === "string") {
    myString.charAt(0); // ok
}

Upvotes: 4

Related Questions