Search code examples
javascripttypescriptnestjs

Why is order of optional parameters causing problems?


I found out a little problem in my nest.js.

I have this function call and the first one is not working and the second one is good. The problem is with ip. I am calling this function from many places. My tsconfig has everything turned on true and didn't mention that it is a problem.

Why? Can somebody explain, please?

  async updateUser(
    userId: string,
    dto: myDto,
    ip?: string,
    isRegistration: boolean = false
  ): Promise<boolean> {}
  async updateUser(
    userId: string,
    dto: myDto,
    ip: string | null = null,
    isRegistration: boolean = false
  ): Promise<boolean> {}

Solution

  • op?: string is short for op: string | undefined.

    When you omit the op argument in a function call, then you get this:

    Code version Result when omitting the op argument in a call
    op?: string undefined
    op: string | null null

    Depending on the updateUser function body this probably will lead to different behaviour.