microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.84k stars 12.46k forks source link

Cannot reassign undefined to the parameter of a function parameter destructuring with default value #60279

Open otomad opened 1 week ago

otomad commented 1 week ago

πŸ”Ž Search Terms

"function parameter destructuring", "destructured parameter", "named parameter", "undefined"

πŸ•— Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?target=0&ts=5.7.0-dev.20241018#code/GYVwdgxgLglg9mABGOAnAtgQwDYAVOqboCmUxqAYuNPGABQEDmAXIgEZxzbGZIA+icABNiwGGGJDEAXkRRUIYgEpEAbwBQiLYiaI+fWcNHjJAbnUBfdetCRYCRCIDO8kNBCpJ+QiTKVq9vSqOqiMMnIKxIgWrMFMrBxcPPyCYCJiElIWKhoAkLr6hmnGmeZWNgG0jsQuCu6eQgDyAA6BON5EpORUdrR0caHhrlExaiGMAPwJnNy80Tnq+YOFqekmQmXWtjQOzq71XgSdfj07YACM-eNDkTpO7DPJeqslktGx49NJcwJGGW-ZNSLAoGF7-DaWLaVXY1fZQDyHHxdfy9BAAJiuulGAxYD2+KT+62i4RxrGG8yBSzCK0JpUhQA

πŸ’» Code

function normalParameterFunction(arg: boolean | undefined = true) {
    arg ||= undefined;
}

function destructuredParameterFunction({ arg = true }: { arg: boolean | undefined }) {
    arg ||= undefined;
}

function destructuredOptionalParameterFunction({ arg = true }: { arg?: boolean }) {
    arg ||= undefined;
}

πŸ™ Actual behavior

The normalParameterFunction works fine, but in destructuredParameterFunction and destructuredOptionalParameterFunction, I cannot assign undefined to arg.

Type 'undefined' is not assignable to type 'boolean'.

πŸ™‚ Expected behavior

I know that if I specify the default value to the arg, the arg will no longer be undefined, but maybe I can reassign it to the undefined.

I guess it should have the same logic as the following:

var arg: boolean | undefined = true;
arg ||= undefined;

Additional information about the issue

function destructuredParameterFunction2({ arg }: { arg: boolean | undefined } = { arg: true }) { arg ||= undefined; }

RyanCavanaugh commented 1 week ago

Prior feedback was that people felt that something with a default should be thought of as "not ever undefined" and that's the current logic. There's a lot of different interpretations on exactly how parameter and destructuring defaults should be thought of (i.e. equivalent to the caller having never passed undefined in the first place vs being a short-circuit assignment at the top of the function).