language-tools: Property with an initial default value can get a undefined excluding TypeScript type while still becoming undefined during runtime
Describe the bug
According to https://github.com/sveltejs/svelte/issues/4442 props’ default values are really initial values as they are only used when a component is first created. While I consider this, as well as others who’ve created issues bevore me, to be a rather unintuitive design decision, I assume there to be good reasons for it.
However, after spending over half a day tracking down this issue from an obscure exception thrown in a production app, I think it remains at least a bug in Svelte’s TypeScript implementation. We were able to type an optional property that had an initial value with a type that excludes undefined. However, the value of that property may very much become undefined during runtime.
To be specific, I belive I should not be able do this:
<script lang="ts">
export let optional: string = "this may be undefined, since this is 'only' an inital value!"
</script>
This is essentially a loaded footgun.
While I rate this as an annoyance, I cannot stress enough how much this defeats the core reason we use TypeScript in the first place.
If this will not be fixed, are there some ways to automatically prevent such flawed uses, i.e. intital values when they really should be a default?
This exact problem has been described in a comment before, as well in this issue in sveltejs language-tools. The reason to close the latter, is pretty murky to me.
Reproduction
This is a short repro simplified from our use case, unfortunately the repl does not support TypeScript. https://svelte.dev/repl/1448697c1adc4f31b658f5207747dece?version=3.29.4
Logs
No response
System Info
System:
OS: Linux 6.1 NixOS 23.05 (Stoat) 23.05 (Stoat)
CPU: (4) x64 Intel Xeon Processor (Skylake, IBRS)
Memory: 10.71 GB / 15.26 GB
Container: Yes
Shell: 3.6.4 - /run/current-system/sw/bin/fish
Binaries:
Node: 20.9.0 - /nix/store/a1hckfqzyys4rfgbdy5kmb5w0zdr55i5-nodejs-20.9.0/bin/node
npm: 10.1.0 - /nix/store/a1hckfqzyys4rfgbdy5kmb5w0zdr55i5-nodejs-20.9.0/bin/npm
Severity
annoyance
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 1
- Comments: 16 (6 by maintainers)
As stated earlier, this would be a huge breaking change (many people’s projects would be littered with type errors), which is why we’re not fixing this for Svelte 4.
Honestly, I would say this is more than just an annoyance. When you’re just working on your own code, it’s an annoyance. When you’re working with libraries that aren’t aware of this issue, it’s a proper minefield. Could I go in and submit a PR for everything I come across? Sure. But I’m sure that 99% of the issues are because Svelte made a choice that is unwise in retrospect.
https://svelte.dev/repl/b71c5df8c24c4221a1c8b13184455375?version=3.46.6
Svelte 5 will use the fallback value everytime the prop becomes undefined, therefore closing