typescripteslintreact-typescripttypescript-eslint

Typescript generating a variable for ...rest parameters before import statement, causing es-lint import/first error


I'm running into an es-lint error (import in body of module) when compiling the code for components using ...rest to spread props.

What I'm trying to do is create components that have defaults set for some of the props without using defaultProps (I'm getting console log warnings that this will be this will be removed in future releases).

The following is an example of how I've written the components:

ButtonTest.tsx:

type ButtonTestProps = {
  style?: string;
  label: string;
};

// By default this component should have the style "border"
export function ButtonTest({ style = "border", ...rest }: ButtonTestProps) {
  const { label } = rest;
  return (
    <button className={style === "border" ? "border-4 border-blue" : ""}>
      {label}
    </button>
  );
}

This file doesn't throw any errors with es-lint, however when Typescript compiles this to JavaScript, it creates a variable to define(?) ...rest at the top of the file before it imports jsx, which causes an es-lint error ("Import in body of module; reorder to top import/first"):

ButtonTest.js:

var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
export function ButtonTest(_a) {
    var { style = "border" } = _a, rest = __rest(_a, ["style"]);
    const { label } = rest;
    return (_jsx("button", { className: style === "border" ? "border-4 border-blue" : "", children: label }));
}
//# sourceMappingURL=ButtonTest.js.map

I've tried saving and restarting the compiler to the same result. I know I could probably fix this by disabling es-lint for the file but I really want to understand why this is happening and if it's because I'm doing something wrong.

Is there some way I could configure the sourcemapping/typescript compiler to avoid this error or is there a problem with how I'm trying to set up with the default component props?

I'd really appreciate it if anyone could offer some advice or insight into this! And if more information is needed about the problem I'd be happy to provide it.


Solution

  • Don't run ESLint on transpiled output JavaScript files (https://typescript-eslint.io/troubleshooting/faqs/javascript#should-i-run-eslint-on-transpiled-output-javascript-files). Source TypeScript files have all the content of output JavaScript files, plus type annotations. There's no benefit to also linting output JavaScript files.