svelte icon indicating copy to clipboard operation
svelte copied to clipboard

`@typescript-eslint/unbound-method` triggered when destructuring function from arg

Open Stadly opened this issue 1 year ago • 0 comments

Describe the bug

When destructuring a function out of a function argument, for example like this:

// `resolve` is a function that is destructured out of the function argument
async function handle({ event, resolve }) {
  // ...
}

ESLint yells at me:

error  Avoid referencing unbound methods which may cause unintentional scoping of `this`.
If your function does not access `this`, you can annotate it with `this: void`, or consider using an arrow function instead  @typescript-eslint/unbound-method

Destructuing the function argument is very common, and is the way it's done in both the Docs and Tutorial for the handle hook.

I don't think resolve uses this, so I think the issue would be solved by declaring Handle like this (using arrow function):

export type Handle = (input: {
  event: RequestEvent;
  resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>;
}) => MaybePromise<Response>;

or this (annotating with this: void):

export type Handle = (input: {
  event: RequestEvent;
  resolve(this: void, event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<Response>;

instead of this:

export type Handle = (input: {
  event: RequestEvent;
  resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<Response>;

Note: The same issue applies to some other functions. At least parent in LayoutLoad and PageLoad comes to mind.

Reproduction

Set up SvelteKit with ESLint and @typescript-eslint/recommended-type-checked.

Set up a handle hook:

// src/hooks.server.js
import type { Handle } from "@sveltejs/kit";

export const handle: Handle = async ({ event, resolve }) => {
  return await resolve(event);
}

Logs

No response

System Info

System:
    OS: Linux 5.15 Debian GNU/Linux 12 (bookworm) 12 (bookworm)
    CPU: (16) x64 Intel(R) Xeon(R) W-11955M CPU @ 2.60GHz
    Memory: 4.39 GB / 15.23 GB
    Container: Yes
    Shell: 5.2.15 - /bin/bash
  Binaries:
    Node: 20.17.0 - /usr/local/bin/node
    Yarn: 1.22.22 - /usr/local/bin/yarn
    npm: 10.8.2 - /usr/local/bin/npm
  npmPackages:
    svelte: ^4.2.19 => 4.2.19 


### Severity

annoyance

Stadly avatar Oct 02 '24 07:10 Stadly