Isolated declarations inconsistent about banning default assignment patterns for function parameters
lucacasonato opened this issue Β· comments
Luca Casonato commented
π Search Terms
- isolated declarations
- function parameter
- default value
π Version & Regression Information
5.5.0-dev.20240514
β― Playground Link
π» Code
export function y(array: number[] = [], comparator: (a: number, b: number) => number): void {};
export const x = {
y(array: number[] = [], comparator: (a: number, b: number) => number): void {}
}
π Actual behavior
For function x
and y
no diagnostic is raised on the property array
at all.
For method z.x
, a diagnostic is raised on array
regarding the type annotation of array
not including undefined
. For method z.y
, no diagnostic is raised.
π Expected behavior
I would expect that in all four cases to raise an ID diagnostic on array
, with the only possible fix being marking comparator
as optional, or adding a default value assignment.
This is for multiple reasons:
- The diagnostic raised for
z.x
suggests changing the type annotation toT | undefined
. This is because without ID, TypeScript would automatically add| undefined
to the emitted declarations. However, this is a bad suggestion, as doing so does not just change the external signature of the function, but also changes the type for the parameter of the function, in the function body, to a new type that does not match with the actual type of the parameter in the function (it can never beundefined
in the body itself, because anyundefined
value would be replaced with the default argument). - An isolated declarations emitter can not determine whether it is safe to emit this or not, because knowing that requires knowing whether the type of
array
containsundefined
. See