Search code examples
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!