Skip to content

invalid-binding error in odd places #8107

@brunnerh

Description

@brunnerh

Describe the bug

I tried to fix a typing issue here by extracting the index access to a @const but this raised an invalid-binding in a place where I would not expect it and also did not raise it where I would have expected it.

Reproduction

<script lang="ts">
    import Attribute from './attribute.svelte';

    type Field = string | number | boolean;
    type FieldArray = Array<Field>;

    function isFieldArray(value: Field | FieldArray): value is FieldArray {
        return Array.isArray(value);
    }

    type ExampleObject = {
        document: Record<string, Field | FieldArray>;
    };

    const obj: ExampleObject = {
        document: {
            name: 'John',
            age: 30,
            isMarried: true,
            hobbies: ['coding', 'reading', 'gaming']
        }
    };
</script>

{#each Object.keys(obj.document) as k}
    {@const value = obj.document[k]}
    {#if isFieldArray(value)}
        {#each value as _, index}
            <!-- Cannot bind to a variable declared with {@const ...} -->
            <input bind:value={value[index]} />
        {/each}
    {:else}
        <!-- No error here -->
        <Attribute bind:value={value} />
    {/if}
{/each}
<!-- attribute.svelte -->
<script lang="ts">
	export let value: string | number | boolean;
</script>
{value}

The first binding accesses value[index] and thus does not try to re-assign value itself, yet there is an error.
The second binding should try to re-assign value, yet there is no error.

Logs

No response

System Info

System:
    OS: Windows 10 10.0.19045
    CPU: (12) x64 Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
    Memory: 18.14 GB / 31.92 GB
  Binaries:
    Node: 16.16.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 6.14.13 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 108.0.5359.99
    Edge: Spartan (44.19041.1266.0), Chromium (108.0.1462.46)
    Internet Explorer: 11.0.19041.1566
  npmPackages:
    svelte: ^3.54.0 => 3.54.

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions