Search code examples
typescripteslinteslintrceslint-config-airbnb

How to handle ESLint error during type casting of document.getElementById() method in TypeScript?


According to all of these pages:

I expected this to work:

/**
 * Destroy current user session.
 */
function logOut() {
  const form = document.getElementById('logout-form') as HTMLFormElement;
  form.submit();
}

Instead, I see this ESLint error in VS Code:

Parsing error: Unexpected token, expected ";"

enter image description here

This approach threw errors, too: const form = <HTMLFormElement>document.getElementById('logout-form');

I've tried this same function in both a .tsx file and a .ts file.

What am I doing wrong?

P.S. I'm using Prettier and ESLint and https://github.com/airbnb/javascript rules and https://stackoverflow.com/a/64166241/470749


Solution

  • https://khalilstemmler.com/blogs/typescript/eslint-for-typescript/#Installation-and-setup was super helpful.

    I think the main key was to change parser in my .eslintrc.js file to parser: '@typescript-eslint/parser',.

    I also adjusted plugins and extends as instructed.

    Then I added these lines to the rules object in my .eslintrc.js because of https://stackoverflow.com/a/64024916/:

    // We must disable the base rule (since it can report incorrect errors) and replace it (https://stackoverflow.com/a/64024916/):
    'no-use-before-define': 'off',
    '@typescript-eslint/no-use-before-define': ['error'],