msanford msanford - 1 year ago 61
TypeScript Question

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
.catch(error => this.displayError(error));

the TypeScript linter warns that Parameter
is implicitly of type
. 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.)

Answer Source

You can use either of these in TypeScript:

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


.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:


Much simpler!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download