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
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:
this is an example of the nullable parameter in TypeScript:
Other Reason:
attentions that A required parameter cannot follow an optional parameter.
correct example
wrong example
you can read more in this link!
op?: string
is short forop: string | undefined
.When you omit the
op
argument in a function call, then you get this:op
argument in a callop?: string
undefined
op: string | null
null
Depending on the
updateUser
function body this probably will lead to different behaviour.