Patrick Quigley
Patrick Quigley

Reputation: 424

How do I type a Svelte component instance variable correctly?

I'm learning how to Svelte, specifically how to bind to a component instance currently in the tutorial here: https://svelte.dev/tutorial/component-this

I'm trying to convert the tutorial to Typescript as I go.

I'm getting an error from the Typescript compiler (ran through 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 Error

./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

I don't understand how to get TS to compile error free here. Can anyone help?

Upvotes: 2

Views: 1111

Answers (1)

Tonton-Blax
Tonton-Blax

Reputation: 515

There is no error in this code, check this stackblitz implememtation

What you could do since this likely is a tooling issue:

  • Have a look at tsconfig.json, svelte.config.js and compare them to yours.
  • run a npm update at the root of your app
  • Check that your node version is at least 16.14 and just for the kicks, event if it is, update it to LTS

Upvotes: 0

Related Questions