Skip to content
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

Type safety for two way binding #1420

Closed
seancolsen opened this issue Mar 22, 2022 · 1 comment
Closed

Type safety for two way binding #1420

seancolsen opened this issue Mar 22, 2022 · 1 comment

Comments

@seancolsen
Copy link

Problem

  • Let's say I have a NumberInput.svelte component which accepts user input, somewhat like <input type="number"/>

    <script lang="ts">
      export let value: number | null = null;
    
      // etc...
    </script>
    
    <!-- 
      etc...
    -->

    Notice that value has type number | null because it becomes null when the user clears the contents of the input field.

  • Now I use that component inside MyForm.svelte as follows:

    <script lang="ts">
      import NumberInput from './NumberInput.svelte';
    
      let quantity = 1;
    </script>
    
    <NumberInput bind:value={quantity} />
    <!--                     ^^^^^^^^  I would like to see an error here.
    -->

    Here quantity has type number.

  • Currently this code does not produce any type errors. That's problematic because the two way binding may set quantity to null at runtime, and it's hard to see that from within MyForm.svelte.

Proposed solution

  • I'd like to see a type error at the specified location because quantity has type number whereas value has type number | null.

  • I would fix the type error inside MyForm.svelte as follows:

    let quantity: number | null = 1;

Alternate solutions

  • Perhaps the type of quantity could be inferred to be number | null. I'm not sure though.
  • I'm open to other approaches or other advice on how people have solved similar issues.
@dummdidumm
Copy link
Member

Duplicate of #1392 (although I like your title much better, so I updated it in #1392)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants