-
Notifications
You must be signed in to change notification settings - Fork 12.8k
TS doesn't allow optional param destructing in spite of having a default value assigned #35160
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
TypeScript is doing what you told it to do: you wrote You can write this instead if you meant it to be optional: const f: F = ({ bar }: { bar?: {} | undefined } = {}) => {
} |
@RyanCavanaugh Besides |
Contextual typing can change the type of a parameter, but can't change its optionality. |
@RyanCavanaugh Exactly, so adding
? It's type is derived from |
This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow. |
@typescript-bot It's still not clear to me whether this really is a question or a bug, as my last comment hasn't been answered. Please don't close until there's a unanimous conclusion about it. |
TypeScript Version: 3.7.2
Search Terms:
default optional parameters destructing
Code
Expected behavior:
Both functions:
f
andg
should be compiled without errors.foo
is optional, but it's also provided a default value; same withbar
. Therefore bothfoo
andbar
are in fact neverundefined
. Btw this also works in vanilla js, tested with all sorts of parameter types.Actual behavior:
TS error is thrown for the
f
function's destructuring of the optional param:This error does sound right, but shouldn't occur taking into consideration those three facts:
foo
isundefined
(= not passed as an argument to the function), the default value kicks in, sofoo
becomes{}
. It's safe to accessbar
then.g
does exactly the same logic asf
, yet it doesn't fail compilation.bar
in vanilla js.Playground Link:
http://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=11&pc=2#code/C4TwDgpgBAYlC8UDeAoKUAUAzA9jg-AFzJQBGAhgE5HIC+tAlMQG44CWAJirSigMY4AdgGdgULMTiIMSMlSi0EdBggB8yXj35DRUAOaSl2PEqSM1G9AJFjZFSgqW4c3IA
The text was updated successfully, but these errors were encountered: