Carlinhos Carlinhos - 28 days ago 7
TypeScript Question

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
}

Answer

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
}