Zoeken op website

javascript - Hoe typ ik een Svelte-component instantievariabele correct?


Ik leer hoe ik Svelte moet gebruiken, specifiek hoe ik kan binden aan een componentinstantie die momenteel in de tutorial staat hier: https://svelte.dev/tutorial/component-this

Ik probeer de tutorial stap voor stap naar Typescript om te zetten.

Ik krijg een fout van de Typescript-compiler (uitgevoerd via ESLint).

Code

<!-- ./ComponentInstance.svelte -->
<script lang="ts">
    import InputField from './Input.svelte';

    // field is the child component!
  let field: InputField;
</script>

<!-- bind this component to a variable -->
<InputField bind:this={field} />

<!-- errors here from field.focus() -->
<button on:click={() => field.focus()}> Focus field </button> 




<!-- ./Input.svelte -->
<script lang="ts">
    // Binded to the HTML input element.
    let input: HTMLInputElement;

    // export a function as a property.
    export function focus() {
        // focus on the variable, which focuses the HTML element as they're bound
        input.focus();
    }
</script>

<!-- bind the element to a variable -->
<input bind:this={input} />
pq@pq:~/src/personal/gitlab/l

TS-fout

./src/lib/bindings/ComponentInstance.svelte
  12:25  error  Unsafe return of an `any` typed value  @typescript-eslint/no-unsafe-return
  12:25  error  Unsafe call of an `any` typed value    @typescript-eslint/no-unsafe-call

Ik begrijp niet hoe ik TS hier foutloos kan laten compileren. Kan iemand helpen?

Antwoord #1

Er is geen fout in deze code, bekijk deze stackblitz-implementatie

Wat je zou kunnen doen aangezien dit waarschijnlijk een probleem met de tooling is:

  • Kijk eens naar tsconfig.json, svelte.config.js en vergelijk ze met die van jou.
  • voer een npm update uit in de root van je app
  • Controleer of je node-versie ten minste 16.14 is en gewoon voor de lol, zelfs als dat zo is, werk deze bij naar LTS