javascripttypescripteslinttypescript-typingstslint

Why TypesScript allows an invalid comparison - boolean === undefined?


Faced with the strange behavior of TS.

const isItLanding = false;

if (isItLanding === undefined) { // valid
  return ...;
}

But here

const isItLanding = 1;

if (isItLanding === 'undefined') { // error
  return ...;
}

Why doesn't TS insure against writing invalid comparisons? And how can I change this behavior?

My TS config looks like:

{
  "compilerOptions": {
    "strict": true,
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "importsNotUsedAsValues": "error",
    "allowSyntheticDefaultImports": true,
    "incremental": true,
    "tsBuildInfoFile": ".next/cache/.tscache/",
    "jsx": "preserve",
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["src/*"],
      "test-utils": ["./src/client/test-utils"]
    }
  },
  "exclude": ["node_modules", "cypress"]
}

Solution

  • I found the right rule in the linter at https://typescript-eslint.io/rules/no-unnecessary-condition. This completely solves the problem!

    You can then use it in your eslint.config.mjs file like:

    // @ts-check
    
    import eslint from "@eslint/js"
    import tseslint from "typescript-eslint"
    
    export default tseslint.config(
        eslint.configs.recommended,
        tseslint.configs.recommendedTypeChecked,
        {
          languageOptions: {
            parserOptions: {
              projectService: true,
              tsconfigRootDir: import.meta.dirname,
            },
          },
        },
        {
            rules: {
                "@typescript-eslint/no-unnecessary-condition": "error",
                // Other rules e.g. ...
                "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_$" }],
            },
        },
    )
    

    You will need to have the following packages installed:

    If you are using Visual Studio Code then you can also install the eslint extension to get these errors to show in your IDE.