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;
}
This does not disable TypeScript rules and should not be used in files ending in .tsx. It does work in .js or .jsx files in projects with TypeScript-ESLint enabled or with standard ESLint enabled. Here’s an example where the myName const is never used and I disable the ESLint warning. Notice the specifier of no-unused-vars.
Then when is more opinionated, so take that with a grain of salt. The Resources section has a Code Sandbox link with live tutorial code that shows these rules being used. There are two primary commands for ignoring the next TypeScript line: @ts-ignore: Ignore a single line with @ts-ignore.
The most important guideline: if you plan to fix code instead of leaving suppression errors, then use @ts-expect-error. If you are using ESLint and you need to disable the next line, use this code: This does not disable TypeScript rules and should not be used in files ending in .tsx.
Ignore ‘normal’ (non-TypeScript) ESLint rules: ignore multiple lines with /* eslint:disable */ and /* eslint:enable */ Here I specified the no-unused-vars command to disable. Once the offending section is over, don’t forget to re-enable the rule. Also, eslint-disable can be used at the top of a file to turn off linting for the whole file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With