Hi @Yunfei_Xie !!
In TypeScript, when you define multiple function overloads, the implementation signature is typically more permissive than the overload signatures. In this case, the last function overload has three parameters, but it allows for optional and default parameter values.
When you call the functionWithOverload
function with three arguments (1, "test", "test"
), TypeScript tries to match the provided arguments with the available overload signatures. It starts from the top and checks if any overload signature is a valid match. In this case, the first two overload signatures don’t match because they expect fewer parameters.
Since the third overload signature allows for three parameters (with the third parameter being optional), TypeScript tries to match the call with this signature. However, it encounters a problem because the second parameter, "test"
, is not assignable to the type string | undefined
(since string
is not compatible with string | undefined
).
To make the call with three parameters work, you would need to modify the implementation of the last function overload to handle the third parameter properly, such as checking if param3
is undefined
or not, and returning the appropriate value.
Here’s an example modification to make the call with three parameters work:
function functionWithOverload(param1: number): boolean;
function functionWithOverload(param1: number, param2: string): string;
function functionWithOverload(param1: number, param2: string = "default", param3?: string): boolean | string {
if (param3 !== undefined) {
return true;
} else if (param2 === "test") {
return "test";
}
return false;
}
console.log(functionWithOverload(1, "test", "test")); // Outputs: "test"
Now, the modified implementation handles the case where the third parameter is provided, and it returns the expected result.
I hope it helps. Happy Learning