Home > Net >  [Syntax Help]What is "variable : () => " meaning in Typescript or JavaScript
[Syntax Help]What is "variable : () => " meaning in Typescript or JavaScript

Time:06-28

I was reading a source code about next-firebase-auth.

I am confused about the following code syntax

export const useAuthUser: () => AuthUserContext

export const verifyIdToken: (token: string) => Promise<AuthUser>

The right side look like an arrow function. The left side is declaring varibles. Intuitively, I am thinking is the same as the following:

export const useAuthUser = () => AuthUserContext

However, it doesn't. I did some test on Chrome console. Here is the code

adder : () => (a   b)

When I hit enter, it shows

() => (a b)

But If I type adder, it shows

Uncaught ReferenceError: adder is not defined

I looked other posts here. It seems like the colon (:) is related to type annotation. So does it mean the right side is a type or interface? But how is an arrow function type or interface? It does not make sense.

Thanks for your help!

CodePudding user response:

The stuff after the colon is the type. As a type, () => AuthUserContext means a function that doesn't require any arguments, and which returns an AuthUserContext. (token: string) => Promise<AuthUser> Means a function that requires a single argument which is a string, and then returns a Promise that will resolve to an AuthUser

The lines of code you showed seem incomplete. Typically, a const will immediately followed by an assignment, as in:

export const useAuthUser: () => AuthUserContext = () => {
  // some code which returns an AuthUserContext
}

I did some test on Chrome console.

The console only supports javascript, not typescript

  • Related