How to prevent "@typescript-eslint/unbound method" errors on non-class TypeScript interfaces?

Viewed 9366

The code below doesn't use classes or this. How can I prevent typescript-eslint errors in function-only (no classes) code? I know I can disable the rule globally, but the rule is useful for class code. I know I can disable it one line at a time, but that seems like a pain given how common it is to have callback functions defined in TS interfaces. Is there another way?

Here's a simplified example of the problem:

interface FooProps {
  bar(): void;
}

export function foo(props: FooProps) {
  const { bar } = props;
  // ^^^ Avoid referencing unbound methods which may cause unintentional scoping of `this`.
  //     eslint(@typescript-eslint/unbound-method)
  return bar;
}
1 Answers

This problem was infuriatingly easy to solve by simply replacing bar(): void with bar: () => void.

Example:

interface FooProps {
  bar: () => void;
}

export function foo(props: FooProps) {
  const { bar } = props;  // no lint error
  return bar;
}

I'd always wondered why function-valued members of a TypeScript interface had two different syntaxes. I always assumed that both syntaxes had identical meanings. Now I know better: the bar(): void syntax apparently means "class member function" while bar: () => void means "function-valued property that doesn't use this".

Leaving a Q&A pair here so the next victim won't waste a half hour like I did on this.

Related