简体   繁体   中英

typescript eslint parsing error "]" expected

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 }
}

在此处输入图片说明

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

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

通过更新@typescript-eslint/parser@typescript-eslint/eslint-plugin到 5.0.0 解决

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM