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.

Introduction & Quick Summary
Symptom. The compiler points at an assignment that looks correct:
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:
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": false
}
}A reproduction that shows the two shapes of the same bug:
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.
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
| Approach | Checks at runtime | Type still shows undefined | Use for |
|---|---|---|---|
if (x === undefined) | Yes | Yes | Local, single use |
x ?? fallback | Yes | Yes | Defaults where any value is valid |
Validation function returning T | Yes | Yes | Boundaries: env, HTTP, database rows |
asserts x is T | Yes, if implemented | Yes | Preconditions reused across functions |
x! | No | No, hidden | Only where an invariant is proved elsewhere |
as string | No | No, hidden | Never for this error |
NonNullable<T> | No | No | Type-level cleanup after a real check |
Which flag produces which message:
| Flag | Typical code | Shows up as |
|---|---|---|
strictNullChecks | string | undefined into string | TS2322, TS2345, TS2532 |
noUncheckedIndexedAccess | arr[0], record[key] | TS18048 on use |
exactOptionalPropertyTypes | { a?: string } given a: undefined | TS2375, TS2412 |
strictPropertyInitialization | Class field assigned in a method | TS2564 |
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:
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:
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:
// 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 memberThe 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:
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:
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 UserThis 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:
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 thatundefinedis 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,""andfalseare replaced, so a configured zero becomes a default without any type error to warn you.- Type assertion on
JSON.parse.JSON.parse(s) as Configis unchecked; the type saysstringwhile the value isundefined, and this is the most common way strict mode gets bypassed in a codebase. strict: truein one package of a monorepo only. A shared library compiled without it can declare a return type asstringfor a function that returnsundefined; the consumer inherits the lie.- Upgrading TypeScript mid-branch. Error codes and narrowing behaviour shift between minor versions (for example
??and?.support,unknownincatch), so a large jump can surface hundreds of TS2322s in untouched files. Upgrade on its own commit. exactOptionalPropertyTypesand React props.React.FC<{ title?: string }>plustitle={maybe}fails under this flag; the spread trick or| undefinedin the interface is the fix, not a cast.String(process.env.X). It convertsundefinedinto the literal string"undefined", which satisfiesstringand produces a request toundefined/. Default first, convert second.- Ignoring
TS18048onObject.entries. WithnoUncheckedIndexedAccess, destructuringObject.entries(o)gives[string, V]whileo[key]inside the loop isV | 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 documentationThe TypeScript documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesJSON.parse Unexpected Token: Trailing Commas, Comments and BOM
JSON is stricter than JavaScript and stops at the first byte it cannot read. Which rule each message names, and the parser to use when you cannot fix the producer.
Zod infer vs TypeScript Interfaces: Runtime Validation Gaps
An interface validates nothing, z.infer is the output type and not the input, and Zod 4 renamed the error helpers. What each one actually guarantees.
TypeScript Decorators: Standard vs experimentalDecorators
TS1240 appears when a legacy decorator meets the stage 3 transform, and the reverse breaks NestJS DI. How the two signatures differ and which flag each stack needs.
TS2307 and TS2835: Cannot Find Module Under moduleResolution NodeNext
NodeNext models Node's real resolution, so .js belongs in the source import and exports maps decide what exists. Why bundler resolution hides both errors.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.