skip to Main Content

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> {}

2

Answers


  1. in the first function, you set the ip parameter nullable.
    but in the second one you didn’t set the ip parameter nullable, you set the type string or null and default value null.

    both functions work as you want.

    problem may be in the body of your first function. you used the ip parameter in the body properly, and if it was nullable, it has no value.

    this is an example of the nullable parameter in TypeScript:

    // A function with an optional parameter
    function sayHello(name?: string) {
      if (name) {
        console.log(`Hello, ${name}!`);
      } else {
        console.log("Hello, stranger!");
      }
    }
    
    // We can call the function with or without an argument
    sayHello("Alice"); // Hello, Alice!
    sayHello(); // Hello, stranger!
    

    this is an example of the nullable parameter in TypeScript:

    // A function with a default parameter
    function sayHello(name = "stranger") {
      console.log(`Hello, ${name}!`);
    }
    
    // We can call the function with or without an argument
    sayHello("Alice"); // Hello, Alice!
    sayHello(); // Hello, stranger!
    

    Other Reason:

    attentions that A required parameter cannot follow an optional parameter.

    correct example

    type GreetFunction = (name: string, message?: string) => void;
    

    wrong example

    type GreetFunction = (name?: string, message: string) => void;
    

    you can read more in this link!

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search