Home > Back-end >  typescript eslint parsing error "]" expected
typescript eslint parsing error "]" expected

Time:10-14

Eslint unable to parse this typescript code.

export const swapKeyAndValue = <T extends { [index: string]: string }>(
    obj: T
) => {
    const newObj: { [prop: string]: string } = {}
    for (const prop in obj) {
        newObj[obj[prop]] = prop
    }
    return newObj as { [K in keyof T as T[K]]: K }
}

enter image description here

I am not able to disable eslint on this line or file, as I have to exclude this file in eslint config.

The code itself however work as expected.

eslint config

module.exports = {
    root: true,
    env: {
        es6: true,
        node: true,
    },
    extends: [
        'eslint:recommended',
        'plugin:import/errors',
        'plugin:import/warnings',
        'plugin:import/typescript',
        'plugin:@typescript-eslint/recommended',
        'plugin:prettier/recommended',
    ],
    parser: '@typescript-eslint/parser',
    ignorePatterns: [
        'dist/**/*', // Ignore built files.
    ],
    plugins: ['@typescript-eslint', 'import'],
    rules: {
        'import/no-unresolved': 'off',
        '@typescript-eslint/explicit-module-boundary-types': 'off',
        '@typescript-eslint/no-explicit-any': 'error',
        camelcase: 'off',
    },
}

typescript: 3.9.7 eslint: 7.32.0

CodePudding user response:

Without the eslint config, it's hard to say for sure, but it sounds like eslint doesn't know that you're using typescript, or doesn't know what specific typescript options / version you're using.

I would ensure that you are using the latest versions of eslint your typescript-eslint plugins, and have something like this in your eslint config:

  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json',
  },

You can read more information about setting up eslint with typescript here

CodePudding user response:

solved by update @typescript-eslint/parser and @typescript-eslint/eslint-plugin to 5.0.0

  • Related