Search code examples
typescriptecmascript-6es6-promise

How to declare types in a fat arrow promise chain?


I'm quite new to TypeScript syntax. Working on existing code like this:

private checkUsername(username: FormControl): boolean {
  return this.userService
    .findUser(username.value)
    .catch(error => this.displayError(error));
}

the TypeScript linter warns that Parameter error is implicitly of type any. Fair enough, but when I try to add what I think looks like type declaration within the fat arrow:

.catch(error:any => this.displayError(error));

the linter warns that it expects a , in place of the :.

I can quell the error by wrapping the parameter and type declaration in parentheses:

.catch((error:any) => this.displayError(error));

Is this because it's expecting a shorthand parameter list with the former syntax (parentheses would therefore be mandatory when declaring type information in this way)?

(Neither What's the meaning of "=>" in TypeScript? (Fat Arrow) nor What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? were particularly useful.)


Solution

  • You can use either of these in TypeScript:

    .catch(error => this.displayError(error));
    

    or

    .catch((error: any) => this.displayError(error));
    

    This, however, is invalid:

    .catch(error: any => this.displayError(error));
    

    That's just the TypeScript syntax rules.

    There is shorthand for what you are trying to do, though:

    .catch(this.displayError);
    

    Much simpler!