宮水の日記

宮水の日記

主に書評や資格取得について記事を書いています。

自動生成されたファイルのESLintのエラーでハマったのでメモ

TypeScriptとReactの環境構築中

eslintの設定をしていたら、自動生成されたファイルのlintエラーにめっちゃハマった。

5:1 warning Missing return type on function @typescript-eslint/explicit-module-boundary-types

App.tsx

import React from 'react';
import logo from './logo.svg';
import './App.css';

//ここをfunctionをやめて型をつけた
const App: React.FunctionComponent = () => {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
};

export default App;

136:8 warning Missing return type on function @typescript-eslint/explicit-module-boundary-types

140:9 error Promises must be handled appropriately or explicitly marked as ignored with the `void` operator @typescript-eslint/no-floating-promises

143:23 error Unsafe member access .message on an any value @typescript-eslint/no-unsafe-member-access

serviceWorker.ts

type Error = {
  message: string;
};

//   warning  Missing return type on function @typescript-eslint/explicit-module-boundary-types
// functionからconstの書き方に変えた
export const unregister = (): void => {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready
      .then((registration) => {
       //  error    Promises must be handled appropriately or explicitly marked as ignored with the `void` operator  @typescript-eslint/no-floating-promises
  // 何も指定しないと返り値が any になってしまうので何か明示しましょうねというエラー(らしい)
        void registration.unregister();
      })
       // テキトーに型をつけてあげた
      .catch((error: Error) => {
       // error    Unsafe member access .message on an any value @typescript-eslint/no-unsafe-member-access
       // テキトーに型をつけてあげた
        console.error(error.message);
      });
  }
};

6:9 error Unsafe assignment of an any value @typescript-eslint/no-unsafe-assignment

7:9 error Unsafe assignment of an any value @typescript-eslint/no-unsafe-assignment

7:23 error Unsafe call of an any typed value @typescript-eslint/no-unsafe-call

全体的にVSCodeで宣言先をみて型をつけてあげた。

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment にしている部分は、試行錯誤した結果ライブラリの型はどうしようもなかったからこうした。

App.test.tsx

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

interface getByTextFunc {
  getByText: (arg1: RegExp) => string;
}

test('renders learn react link', () => {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  const { getByText }: getByTextFunc = render(<App />);
  const linkElement: string = getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

雑ですみません\( ˆoˆ )/