Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TS2322: Type 'string | undefined' Is Not Assignable to Type 'string'

strictNullChecks makes maybe-missing values visible at compile time. Narrow at the boundary, keep ?undefined? honest, and know which flag produces TS18048 instead.

~4 min readTypeScript
#TypeScript#strictNullChecks#Type Safety#Debugging
3D diagram of a solid type block beside a hollow one with a question-mark hole and a rejected arrow, headline TS2322

Introduction & Quick Summary

Symptom. The compiler points at an assignment that looks correct:

code
src/config.ts:14:5 - error TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. 14 timeout: process.env.TIMEOUT_MS, ~~~~~~~

Or, one level down, TS18048: 'config.timeout' is possibly 'undefined' and TS2532: Object is possibly 'undefined'.

Cause. strict enables strictNullChecks, which makes undefined and null members of the type system instead of being assignable to everything. Anything that can legitimately be missing now carries | undefined: process.env.X (always string | undefined), Map.get(), Array.find(), pop(), a JSON field, an optional property. TypeScript will not let that flow into a string without evidence that the undefined case is handled.

Fix. Narrow or supply a value at the point where the type enters your code: an if (x === undefined) throw, a ?? default, a validation function that returns the narrowed type, or a schema parse at the boundary. x! and as string silence the error by asserting what you have not checked, and they move the failure to production, where it reads undefined is not a function.

Core Mechanics, Signatures & Reproducible Setup

strictNullChecks is the switch; a project without it compiles the same code and crashes on the same input:

jsonc
// tsconfig.json { "compilerOptions": { "strict": true, "noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": false } }

A reproduction that shows the two shapes of the same bug:

ts
interface Config { baseUrl: string; timeout: number; } declare function readEnv(key: string): string | undefined; // TS2322 — undefined in the value const cfg: Config = { baseUrl: readEnv("BASE_URL"), // Type 'string | undefined' is not assignable to type 'string' timeout: Number(readEnv("TIMEOUT") ?? 0), }; // TS18048 — maybe undefined when read declare const maybeCfg: Config | undefined; console.log(maybeCfg.baseUrl.length); // 'maybeCfg' is possibly 'undefined'

Narrowing is flow-sensitive: the check has to dominate the use in the same scope.

ts
function normalize(raw: string | undefined): string { if (raw === undefined) return "http://localhost:3000"; return raw.replace(/\/+$/, ""); // raw is string here } const timeout = readEnv("TIMEOUT") ?? "5000"; // ?? covers null and undefined

?? and || are not interchangeable: || also replaces valid falsy values (0, "", false), so Number(readEnv("RETRIES") || 3) turns a configured 0 into 3.

Key Comparison Table

ApproachChecks at runtimeType still shows undefinedUse for
if (x === undefined)YesYesLocal, single use
x ?? fallbackYesYesDefaults where any value is valid
Validation function returning TYesYesBoundaries: env, HTTP, database rows
asserts x is TYes, if implementedYesPreconditions reused across functions
x!NoNo, hiddenOnly where an invariant is proved elsewhere
as stringNoNo, hiddenNever for this error
NonNullable<T>NoNoType-level cleanup after a real check

Which flag produces which message:

FlagTypical codeShows up as
strictNullChecksstring | undefined into stringTS2322, TS2345, TS2532
noUncheckedIndexedAccessarr[0], record[key]TS18048 on use
exactOptionalPropertyTypes{ a?: string } given a: undefinedTS2375, TS2412
strictPropertyInitializationClass field assigned in a methodTS2564

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Environment variables at the boundary

process.env is Record<string, string | undefined> and the single largest source of TS2322 in server code. Validate once, at startup, and let the rest of the program see plain string:

ts
function required(name: string): string { const value = process.env[name]; if (value === undefined || value.trim() === "") { throw new Error(`Missing environment variable: ${name}`); } return value; } export const env = { databaseUrl: required("DATABASE_URL"), port: Number(process.env.PORT ?? 3000), } as const;

required returns string, so every later use is narrowed by construction. A schema library does the same for a whole object and gives you the failing key in the message; either way the check happens once instead of at thirty call sites.

2. Map.get() and Array.find() are optional by design

Both return T | undefined because the key may be absent, and a falsy check is wrong when T can be 0, "" or false:

ts
const counts = new Map<string, number>(); counts.set("draft", 0); // Wrong: treats a real 0 as missing const a = counts.get("draft") ? counts.get("draft")! + 1 : 1; // Right: presence, not truthiness const current = counts.get("draft"); const b = current === undefined ? 1 : current + 1; // Also right, one lookup, no non-null assertion const c = (counts.get("draft") ?? 0) + 1;

For find, prefer a guard clause over a fallback object; a fabricated { id: "" } passes the type system and fails in the code that consumes it.

3. Turning on noUncheckedIndexedAccess

This flag makes every index access T | undefined, which is accurate for arrays and records read from outside the program. It typically produces dozens of errors in code that was fine, and the fixes cluster into three shapes:

ts
// arrays: iterate, do not index for (const row of rows) { consume(row); } // row is Row, not Row | undefined // first/last element const first = rows[0]; if (first === undefined) throw new Error("empty result set"); // records keyed by known string unions type Status = "draft" | "live"; const labels: Record<Status, string> = { draft: "Draft", live: "Live" }; labels["draft"]; // no undefined: key is a union member

The last line is the important one: a Record with a closed key type is not affected, so preferring union keys over string removes the error instead of annotating around it.

4. exactOptionalPropertyTypes and the undefined distinction

Under this flag foo?: string means "the property may be absent", not "the property may be undefined". Passing foo: undefined explicitly is an error, which breaks the common pattern of forwarding an optional value:

ts
interface Options { title?: string } // TS2375 with exactOptionalPropertyTypes const o: Options = { title: maybeTitle }; // Fix A: omit the key const o2: Options = { ...(maybeTitle !== undefined && { title: maybeTitle }) }; // Fix B: declare the honest type interface OptionsB { title?: string | undefined }

Pick one convention per project; mixing them produces the same error in a different file each week.

5. Assertion functions instead of non-null assertions

When the same precondition repeats, an assertion function keeps the check and the narrowing together:

ts
function assertDefined<T>(value: T | undefined, name: string): asserts value is T { if (value === undefined) throw new Error(`${name} is not defined`); } const user = users.get(id); assertDefined(user, `user ${id}`); sendEmail(user.email); // user is User

This throws at the call site with a useful name, rather than deferring to TypeError: Cannot read properties of undefined three frames deeper. Assertion functions need an explicit type annotation and a const (or a property that is never reassigned) as the argument.

6. Generics, NonNullable, and satisfies

NonNullable<T> deletes null | undefined from a type without checking anything. It belongs after a real check, for example on the result of a validated lookup, never as the first tool:

ts
type Row = { id: string; email: string | undefined }; function withEmail(rows: Row[]): NonNullable<Row["email"]>[] { return rows.map((r) => r.email).filter((e): e is string => e !== undefined); } const routes = { home: "/", post: "/blog/:slug", } satisfies Record<string, `/${string}`>;

satisfies checks the literal against a type while keeping the narrow inferred type, so routes.post stays "/blog/:slug" rather than widening to string.

Common Compilation/Runtime Mistakes & Version Gotchas

  • ! to clear TS2322. It asserts that undefined is impossible; on the one request where the field is missing, the crash appears in a different service than the one that compiled the lie.
  • || where ?? is meant. 0, "" and false are replaced, so a configured zero becomes a default without any type error to warn you.
  • Type assertion on JSON.parse. JSON.parse(s) as Config is unchecked; the type says string while the value is undefined, and this is the most common way strict mode gets bypassed in a codebase.
  • strict: true in one package of a monorepo only. A shared library compiled without it can declare a return type as string for a function that returns undefined; the consumer inherits the lie.
  • Upgrading TypeScript mid-branch. Error codes and narrowing behaviour shift between minor versions (for example ?? and ?. support, unknown in catch), so a large jump can surface hundreds of TS2322s in untouched files. Upgrade on its own commit.
  • exactOptionalPropertyTypes and React props. React.FC<{ title?: string }> plus title={maybe} fails under this flag; the spread trick or | undefined in the interface is the fix, not a cast.
  • String(process.env.X). It converts undefined into the literal string "undefined", which satisfies string and produces a request to undefined/. Default first, convert second.
  • Ignoring TS18048 on Object.entries. With noUncheckedIndexedAccess, destructuring Object.entries(o) gives [string, V] while o[key] inside the loop is V | undefined; iterate entries instead of re-indexing.

Related tools. When a tsconfig.json change causes a wall of errors, format both versions with the JSON formatter and diff them with the text diff tool to see which flag flipped, and keep the failing expression and its declared type side by side in the issue.

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.