typescript - 為什麼我的 switch-exhaustiveness-check 代碼檢查規則不起作用?
以下程式碼觸發了標準的 default-case lint 錯誤,但 @typescript-eslint/switch-exhaustiveness-check 並未觸發。有什麼可能的原因嗎?其他 @typescript-eslint 規則運作正常。
type Day = 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday' | 'Saturday' | 'Sunday';
const day = 'Monday' as Day;
let result = 0;
switch (day) {
case 'Monday': {
result = 1;
break;
}
}
這是我的 .eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'plugin:react/recommended',
'airbnb',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
ignorePatterns: ['.eslintrc.js'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json'],
},
plugins: ['react', '@typescript-eslint', 'react-hooks'],
// Fix error "Unable to resolve path to module" for tsx files
settings: {
'import/resolver': {
typescript: {},
},
},
rules: {
// Fix "React used before defined" error
'no-use-before-define': 'off',
'@typescript-eslint/no-use-before-define': ['error'],
// Allow jsx
'react/jsx-filename-extension': ['warn', { extensions: ['.tsx'] }],
// Fix error "Missing file extension tsx"
'import/extensions': [
'error',
'ignorePackages',
{
ts: 'never',
tsx: 'never',
},
],
// Fix error "‘Enum’ is already declared in the upper scope"
'no-shadow': 'off',
'@typescript-eslint/no-shadow': ['error'],
// Add rules for react hooks
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
// Use 120 character windows
'max-len': [
'error',
{
code: 120,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true,
},
],
// Stop using default export
'import/no-default-export': 'error',
'import/prefer-default-export': 'off',
// Since we use interfaces often in DDD and sometimes an implemented function uses this and sometimes not, it makes
// this rule impractical.
'class-methods-use-this': 'off',
// Require accessibility modifiers on everything except public constructors
'@typescript-eslint/explicit-member-accessibility': ['error', { overrides: { constructors: 'no-public' } }],
// We use these many times in domain objects, so it makes sense to ignore them.
'@typescript-eslint/no-empty-interface': 'off',
// Allow test dependencies to appear in devDependencies
'import/no-extraneous-dependencies': ['error', { devDependencies: ['**/*.test.ts', '**/*.test.tsx'] }],
// Place default props inside class field
'react/static-property-placement': ['error', 'static public field'],
'@typescript-eslint/switch-exhaustiveness-check': ['error'],
},
};
答案#1
此規則需要類型資訊才能運行。
你可以在這裡的文件中閱讀更多內容。
將以下屬性添加到你的 eslint 配置中應該可以解決該問題:
module.exports = {
extends: [
'plugin:@typescript-eslint/recommended-type-checked',
],
parserOptions: {
project: true,
tsconfigRootDir: __dirname,
},
};
答案#2
error 實際上並不是 exhaustiveness-check 規則的支援值,只有 warn。這裡是包含可接受值的文件: https://typescript-eslint.io/rules/switch-exhaustiveness-check/
