Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript TS2367: This comparison appears to be unintentional

TS2367 fires when two compared types share no possible values. Fix it with narrowing, literal unions, a discriminant field, or an explicit widening cast.

~6 min readTypeScript
#typescript#ts2367#type-compatibility#type-narrowing
Bold white headline reading TS2367 OVERLAP with a TypeScript type gate rejecting an amber value block on the right.

Introduction & Quick Summary

The compiler stops on a comparison it believes can never be true:

code
error TS2367: This comparison appears to be unintentional because the types '"idle" | "loading"' and '"done"' have no overlap.
code
src/job.ts:24:15 24 if (state === "done") { ~~~~~~

TypeScript evaluates the declared types of both operands. If their value sets share no member, the comparison is either dead code or a stale type, and TS2367 reports it as a likely bug. The fix is almost never as any. It is either widening the type so the comparison becomes meaningful, or deleting the comparison because the state genuinely cannot occur.

Where it appears:

  • Comparing a narrowed variable against a literal outside its union.
  • A reducer or state machine that receives a value from a wider source than the union declares.
  • An enum compared with a plain string literal, or two different enums compared.
  • !== null or !== undefined on a value declared non-nullable.
  • A generated API client that types a status field too narrowly for a real response.

Quick answer: read both sides of the operator, decide which type is wrong, and change that type. Casting the comparison silences the error and keeps the dead branch.

Core Mechanics, Signatures & Reproducible Setup

TypeScript compares assignability in both directions for === and !==. If neither type is assignable to the other, the operands have no common values and TS2367 is raised. The check runs on the narrowed type at that program point, not on the declaration, so earlier guards change the result.

ts
// repro.ts -- compile with: npx tsc --strict --noEmit repro.ts type State = "idle" | "loading"; declare const state: State; if (state === "done") { // TS2367: types '"idle" | "loading"' and '"done"' have no overlap } // an early return narrows the remaining type function isBusy(s: State): boolean { if (s === "idle") return false; return s === "loading"; // fine: s is "loading" here }

The comparison operator family reports related but distinct diagnostics:

CodeMessage shapeTrigger
TS2367types X and Y have no overlap=== or !== between disjoint types
TS2365operator cannot be applied to types X and Y+, <, > on wrong operands
TS2345argument of type X is not assignable to parameter of type Ycall site mismatch
TS2322type X is not assignable to type Yassignment or return
TS5076operator + cannot be applied to X or Ymixing string and number

A switch over every variant with a const unreachable: never = job.status default turns the same check into a compile error when a variant is added, which is the protection TS2367 is reaching for.

Key Comparison Table

ApproachWhat it changesUse when
Widen the declaration to a union that includes the literalthe value set becomes correctthe annotation drifted from the data
Add a discriminant field to the union variantsshapes become distinguishableobjects share keys but differ in meaning
Write a type predicate (x is "done")narrows without a castthe check is dynamic and correct at runtime
Convert both sides (String(x))removes the type relationshipcomparing a value with an external string
as const on a literal mapkeeps literal types instead of wideningbuilding lookup tables from strings
Delete the branchremoves dead codethe type proves the value cannot occur
// @ts-expect-error on one linesuppresses one known-safe comparisona third-party type is wrong and cannot be patched

The table that most often decides the fix is the one comparing annotation versus reality:

SymptomReal causeLowest-risk fix
Error on one literal, others fineliteral missing from the unionadd it, or fix the union source
Error after adding an early returnnarrowing carried a narrower typemove the check before the guard
Error only in teststest fixture typed as production uniontype the fixture with the same union
Error on null checkstrictNullChecks off or value non-nullableremove the check or widen the type
Error on enum comparestring compared with enum memberuse Status.Done, not "done"

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Literal union narrower than the runtime value

The most common cause is a union written by hand that is missing a value the API really returns.

ts
type Status = "idle" | "loading"; // hand-written, incomplete declare const fromApi: Status; if (fromApi === "error") { // TS2367 }

Two honest fixes: extend the union, or derive it from the source of truth.

ts
const STATUSES = ["idle", "loading", "error"] as const; type Status2 = (typeof STATUSES)[number]; function isStatus(value: string): value is Status2 { return (STATUSES as readonly string[]).includes(value); } declare const fromApi2: Status2; if (fromApi2 === "error") { // fine }

Deriving the union from the same array used at runtime keeps the type and the guard in one place, so they cannot drift apart.

2. Missing discriminant on one variant

Object unions without a discriminant field collapse into an unhelpful wide type, and comparisons against a property that only some variants declare fail.

ts
interface Ok { data: string; } interface Failed { error: string; } type Result = Ok | Failed; function handle(r: Result) { if (r.error === "timeout") { // TS2339 first: property does not exist on Ok } }

Add a tag to each variant and the comparison becomes typed and exhaustive:

ts
type Result2 = | { kind: "ok"; data: string } | { kind: "error"; message: string }; function handle2(r: Result2): string { return r.kind === "error" ? r.message : r.data; }

3. Enum compared with a string

String enums are nominal: Status.Done is not the string "done" to the checker, even though both print the same.

ts
enum Status { Idle = "idle", Done = "done", } declare const s: Status; if (s === "done") { // TS2367: types 'Status' and '"done"' have no overlap } if (s === Status.Done) { // fine }

When the value arrives from JSON, parse it into the enum once at the boundary with Object.values(Status).find(...) and throw on an unknown string, instead of casting the comparison.

4. Comparisons with unknown and any

unknown cannot be compared to a literal without narrowing first, and any disables the check entirely, which hides the next real error.

ts
declare const payload: unknown; if (typeof payload === "string" && payload === "done") { // narrow, then compare: no TS2367 } declare const loose: any; if (loose === "done") { // compiles, but nothing is verified }

Prefer unknown at trust boundaries and narrow with typeof or a predicate. The comparison then sits inside a branch where the type is known, which is also where the runtime check belongs.

5. Non-nullable values compared with null

With strictNullChecks on, !== null on a non-nullable type is flagged, and the check is usually a leftover from a time when the value could be null.

ts
interface Config { retries: number; } function use(cfg: Config) { if (cfg.retries !== null) { // TS2367 with strictNullChecks: number and null have no overlap } }

Options: delete the guard, or widen the field to number | null when the null case is real and handled. Widening without handling the null branch just moves the error to the place that should have handled it.

6. Generated clients with over-narrow types

OpenAPI and GraphQL generators sometimes emit literal unions for fields that the server treats as free text. The type is wrong, not the comparison, so patch the generator config or wrap the field.

ts
type Generated = { status: "active" }; function isClosed(g: Generated): boolean { return (g.status as string) === "closed"; }

Wrapping the cast in one small function contains the unsafe step. Regenerating the client with a corrected schema is still the real fix.

Common Compilation/Runtime Mistakes & Version Gotchas

Casting the whole comparison. (state as string) === "done" compiles and keeps the branch, but the branch is still unreachable if the type is right. Decide whether the type or the code is wrong before you cast anything.

Turning off strict to clear the error. TS2367 appears with strictNullChecks and with literal types. Disabling either narrows less and hides bugs elsewhere; the error count usually drops while the runtime error count does not.

Assuming === is always flagged. Values typed as a primitive's base type (string, number, boolean) overlap with every literal of that primitive, so no error is raised. TS2367 appears only when both sides are literal, union, or enum types with no shared member.

Forgetting that narrowing resets. A type guard narrows inside the block only. Reassigning the variable to a wider value inside the block may widen it back on the next statement, and the comparison then behaves differently than it reads.

Comparing template literal types with plain strings. Since TypeScript 4.2, template literal types participate in comparisons. type Path = `/api/${string}`; compared with "/health" has no overlap and is flagged, even though the runtime string may match. Widen to string at the boundary or use a predicate function.

Version differences that change results. --exactOptionalPropertyTypes and --noUncheckedIndexedAccess both turn previously overlapping comparisons into TS2367; apply them in the same commit as the handling code.

Practical workflow. Check an API payload shape in JSON, use Diff to compare an old and a new union before merging, and keep tests compiling with the same tsconfig as production; a test-only override is the usual reason a stale union survives.

Reference material: Type narrowing and Type compatibility.

Official references

primary documentation

The TypeScript documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.