Open LorisSigrist opened 1 year ago
I just had another thought about this.
Instead of magically giving the developer the "type" of the form, consider the opposite. Passing an interface to a form that then gets enforced. This would probably end up less verbose and be a lot closer to the mental model developers have while writing code.
Svelte super forms looks promising. https://superforms.rocks/
Describe the problem
Typescript is kinda bad at knowing what is in a form; Which makes sense since it can't deduce what types certain fields have without having access to the markup.
But, this makes form-handling code very frustrating to write. After doing
const data = new FormData(form)
, you then have to manually type-check every single entry in that form data. This adds a lot of code.Svelte offers the alternative of binding to an input's value, and then using that value instead of a FormData object, but this also has it's problems. Mainly duplication, and all the dangers that come with that. Adding
bind:value={data.name}
to every single input is very cumbersome on large forms, as well as error-prone.For example: When doing the client-side form handling as a progressive enhancement step over a regular form-submit, it is very easy to change a
name
attribute on an input, while forgetting to change it on the manual value binding, leading to nasty bugs.Describe the proposed solution
What Svelte could do
As a compiler, Svelte has a (more or less) God's eye view of all the input-elements that could be in the DOM, as well as what attributes they could have. What type are they?, Are they required?, What's the name?, Are they disabled? etc.
This could allow Svelte to statically figure out what Types of key/value pairs can be in a form, even if the inputs are abstracted away very far down in the Component Tree and nested in conditional statements. It would be nice if such Type-information could be exposed to the developer somehow. This would drastically reduce the amount of redundant type-checking code.
Caveat
If the DOM gets tampered with from outside Svelte's eyes, then static analysis is no longer possible, and types can't be guaranteed. However, as long as developers are made aware of this, I think they can be trusted to handle the generated types responsibly.
Alternatives considered
Simply live with the pain
Importance
would make my life easier