Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: what is the type of a lambda?

In the Angular "Tour of Heroes" tutorial, an error handler method is defined which returns a lambda:

private handleError<T>(operation = 'operation', result?: T) {

  return (error: any): Observable<T> => {
    this.log(`${operation} failed: ${error.message}`);
    return of(result as T);
};

The handleError method has no return type and is therefore inferred. What would the return type be if we wanted to make it explicit? I've tried Function (lib.es2015.core.d.ts) but that doesn't work.

Adding the lambda itself as a return type works, but seems wrong:

  private handleError<T>(operation = 'operation', result?: T): (error: any) => Observable<T> {
          return (error: any): Observable<T> => {
          ...

What is the correct Typescript type for a lambda? In Java, handleError would return a java.util.function.Function. Is there anything similar in Typescript? Thank you.

like image 935
Dave Branning Avatar asked Sep 19 '25 21:09

Dave Branning


1 Answers

In Javascript all functions are of the Function type, so at runtime they are all the same type (unlike Java where they would be different types). Now Typescript does allow you to distinguish between different function signatures, but this is just a compile time distinction, at runtime they will all be Function. The general way we write such a signature is (paramList) => returnType.

In your case the signature of the lambda is already spelled out in the return, so you are corect when you write

 private handleError<T>(operation = 'operation', result?: T): (error: any) => Observable<T> {
      return (error) => { // We can let inference work here, the return type will be enforced.
      ...

You can write a type alias if you find you use the same function signature over and over again, but this is just a short hand for essentially the same thing, a function signature:

type ErrorHandler<T> = (error: any) => Observable<T>
like image 131
Titian Cernicova-Dragomir Avatar answered Sep 22 '25 12:09

Titian Cernicova-Dragomir