TypeScript `OptionalChain` Narrowing in 2026: Why `?.` Does Not Always Narrow the Way You Think It Does
Optional chaining returns undefined for null or undefined values, but TypeScript treats the result as the original type or undefined without narrowing the base union. This breaks type safety in conditional checks, length property tests, and discriminated unions when developers expect `?.` to act as a type guard.
Optional chaining returns undefined for null or undefined values, but TypeScript treats the result as the original type or undefined without narrowing the base union. This breaks type safety in conditional checks, length property tests, and discriminated unions when developers expect ?. to act as a type guard. The ?. operator checks only the left-hand value at runtime while the type system preserves the full union, forcing developers to combine optional chaining with explicit narrowing techniques like the in operator, type predicates, or separate null checks to restore correctness.
TypeScript 3.7 introduced optional chaining as a runtime convenience for accessing deeply nested properties. Developers write foo?.bar?.baz expecting both runtime safety and type narrowing. The runtime behavior delivers on the first promise, short-circuiting at the first null or undefined. The type system fails the second. When a conditional checks foo?.bar.length > 0, TypeScript still considers foo possibly undefined inside the branch. The compiler knows the expression evaluates, but it does not know which part succeeded.

Proper narrowing restores type safety. Separating the null check from the property access tells the compiler exactly what succeeded. Writing if (foo && foo.bar.length > 0) or if (foo?.bar && foo.bar.length > 0) establishes the type guard before the branch. The first check narrows foo to a defined value, allowing safe access inside the conditional.

Key Takeaways
- Optional chaining (
?.) short-circuits at runtime but does not narrow the base type in TypeScript's type system. - Using
?.in conditionals leaves the original union type intact, causing "possibly undefined" errors inside branches. - Chaining
?.with.lengthor other properties prevents TypeScript from recognizing the value as defined. - Explicit null checks (
if (foo && foo.bar)) or theinoperator narrow types correctly before accessing properties. - Combining optional chaining with separate type guards restores type safety without sacrificing runtime convenience.
Why ?. Does Not Narrow Types in TypeScript
Optional chaining performs a runtime check that stops execution when encountering null or undefined. The type system models this as T | undefined where T is the target type. When the base value is a union like Foo | undefined, the resulting type becomes Bar | undefined where Bar is the accessed property's type. TypeScript never removes the undefined from the union based on the ?. operator alone.
This behavior differs from truthiness checks using &&. Writing foo && foo.bar establishes a control flow that TypeScript recognizes. The first check narrows foo from Foo | undefined to Foo. The second access proceeds safely. Optional chaining collapses the entire expression into a single operation, leaving the type system without discrete narrowing points.
The TypeScript 3.7 release notes describe the runtime semantics clearly: when foo is defined, foo.bar.baz() runs, otherwise the expression returns undefined. The notes do not claim type narrowing. The distinction matters in conditional contexts where developers expect the check itself to prove the value's existence.

The compiler tracks control flow for explicit checks. A standalone if (foo) narrows the type inside the branch. Embedding the check inside foo?.bar removes that signal. TypeScript sees an expression that might return undefined but cannot deduce which part of the chain succeeded.
This limitation surfaces in union types with discriminated properties. When a union has a nullable member, checking foo?.kind === "circle" does not eliminate the null or undefined case. The comparison succeeds only when foo exists and has the discriminant value, but the type system retains the original union. Developers must check foo separately before accessing the discriminant.
The unknown Result Problem: What ?. Actually Returns
Optional chaining on a value typed as unknown produces unknown, not undefined. The TypeScript 3.7 release notes specify that ?. returns undefined when the left-hand side is null or undefined. When the left-hand type is unknown, TypeScript cannot guarantee the runtime value's shape, so the result remains unknown.
This behavior compounds narrowing failures. When a function accepts unknown and uses optional chaining to test for a property, the returned value stays unknown even after the check. Developers must assert the type or use a type predicate to proceed.
function processValue(value: unknown) {
if (value?.toString) {
// Error: value is still unknown here
return value.toString();
}
return "default";
}The function intends to call toString when present. The check value?.toString evaluates to Function | undefined | unknown, depending on the runtime value. TypeScript cannot narrow value from unknown to an object with a toString method based on this check. The developer must write a type predicate or use typeof to establish the shape.
Correcting this requires separating the type assertion from the optional chaining:
function processValue(value: unknown) {
if (typeof value === "object" && value !== null && "toString" in value) {
return value.toString();
}
return "default";
}This version checks the type, eliminates null, and verifies the property exists. Each step narrows the type incrementally. The compiler recognizes the progression and allows the method call.
The unknown case highlights the broader issue. Optional chaining returns a value typed as the accessed property or undefined, but it does not update the base value's type. When the base is unknown, the result remains unknown because the compiler lacks information about the runtime structure. When the base is a union, the result preserves the union without eliminating the nullable case.

Union Type Narrowing Failures with Optional Chaining
Discriminated unions rely on literal types to distinguish variants. TypeScript narrows unions by checking the discriminant property. Optional chaining disrupts this pattern when the union includes null or undefined.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; sideLength: number };
type Shape = Circle | Square | undefined;
function getArea(shape: Shape): number {
if (shape?.kind === "circle") {
// Error: shape is still Shape (Circle | Square | undefined)
return Math.PI * shape.radius ** 2;
}
return 0;
}The check shape?.kind === "circle" evaluates correctly at runtime. When shape is undefined, the expression returns undefined and the branch does not execute. When shape is a Circle, the comparison succeeds. TypeScript does not eliminate undefined from the union inside the branch. The compiler sees a check that might be true for multiple reasons and cannot deduce which variant remains.
The TypeScript narrowing documentation describes discriminated unions as requiring a common property with literal types. Checking the discriminant directly narrows the union to the matching variant. Optional chaining obscures the discriminant check, preventing the narrowing logic from activating.
The solution separates the null check from the discriminant check:
function getArea(shape: Shape): number {
if (shape && shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
return 0;
}This version checks shape exists before accessing kind. The first condition narrows shape from Circle | Square | undefined to Circle | Square. The second condition narrows further to Circle. Each check provides a discrete narrowing step that the compiler tracks through control flow.
An alternative uses the in operator to verify the property exists:
function getArea(shape: Shape): number {
if (shape && "radius" in shape) {
return Math.PI * shape.radius ** 2;
}
return 0;
}The in operator checks for the property at runtime and narrows the type to unions containing that property. This approach works when the discriminant is implicit rather than a literal kind field. TypeScript recognizes in as a type guard and updates the control flow accordingly.
The Length Property Trap: Why Array Checks Break Narrowing
Checking array length with optional chaining causes a specific narrowing failure. Developers expect if (arr?.length > 0) to narrow the type to a non-empty array. TypeScript keeps the type as T[] | undefined inside the branch.
type Container = { items: string[] } | undefined;
function processItems(container: Container) {
if (container?.items.length > 0) {
// Error: container is still Container (possibly undefined)
container.items.forEach((item) => console.log(item));
}
}The check combines optional chaining with a property access and a comparison. At runtime, the condition guards against undefined correctly. The type system sees the full expression container?.items.length > 0 and infers only that the result is boolean. It does not narrow container because the check does not explicitly test container itself.
This pattern appears frequently in React components and API response handlers. Code that worked before introducing optional chaining breaks when the developer assumes the syntax provides type narrowing. The compiler error points to container as possibly undefined, confusing developers who see the length check as proof of existence.
The fix splits the check into separate steps:
function processItems(container: Container) {
if (container && container.items.length > 0) {
container.items.forEach((item) => console.log(item));
}
}The first condition narrows container to defined. The second condition checks the array is non-empty. TypeScript tracks both conditions and understands the branch executes only when container exists and contains items.
Another approach extracts the array first:
function processItems(container: Container) {
const items = container?.items;
if (items && items.length > 0) {
items.forEach((item) => console.log(item));
}
}This version assigns the optional chain result to a variable. The subsequent check narrows the variable's type to string[]. The compiler recognizes the control flow because the check directly tests the extracted value rather than a chained expression.
The length property trap extends beyond arrays. Similar failures occur with string length checks, object property counts, and any pattern that accesses a property through optional chaining then tests the result. The common thread is the compiler's inability to infer which part of the chain succeeded based solely on the final expression's truthiness.
| Pattern | Type After Check | Reason |
|---|---|---|
if (foo?.bar.length > 0) | Foo | undefined | No discrete check on foo |
if (foo && foo.bar.length > 0) | Foo | Explicit null check narrows type |
if (foo?.bar && foo.bar.length > 0) | Foo | First check provides guard |
const bar = foo?.bar; if (bar && bar.length > 0) | Bar | Variable holds narrowed result |
Proper Narrowing Techniques: in, Guards, and Explicit Checks
Type guards provide explicit narrowing that optional chaining cannot. The in operator, type predicates, and separate null checks all signal the compiler to update control flow.

The TypeScript narrowing documentation lists the in operator as a type guard. Checking "property" in value narrows the union to types containing that property. This works for discriminated unions and optional properties.
type Response = { data: string } | { error: string } | undefined;
function handleResponse(response: Response) {
if (response && "data" in response) {
console.log(response.data);
}
}The first check eliminates undefined. The in operator narrows the remaining union to the success case. TypeScript recognizes both steps and allows safe access to data. This pattern works when the discriminant is a property name rather than a literal value.
Type predicates offer stronger guarantees. A predicate is a function returning value is Type, telling the compiler the value matches the specified type when the function returns true.
type ApiResult = { success: true; data: string } | { success: false; error: string };
function isSuccess(result: ApiResult): result is { success: true; data: string } {
return result.success === true;
}
function processResult(result: ApiResult) {
if (isSuccess(result)) {
console.log(result.data);
} else {
console.error(result.error);
}
}The predicate isSuccess returns a boolean at runtime and asserts a type relationship to the compiler. When isSuccess(result) returns true, TypeScript narrows result to the success variant. The predicate encapsulates the discriminant check in a reusable function that provides both runtime and compile-time guarantees.
Explicit null checks remain the simplest solution for most cases. Separating if (value) from subsequent property accesses establishes a clear control flow that TypeScript tracks automatically. This approach requires no special syntax and works with all union types.
type User = { name: string; email: string } | undefined;
function greetUser(user: User) {
if (user) {
console.log(`Hello, ${user.name}!`);
}
}The check if (user) narrows the type to { name: string; email: string }. All property accesses inside the branch are safe. This pattern scales to deeply nested structures by checking each level before accessing the next.
Combining optional chaining with explicit guards captures both benefits. The optional chain provides runtime safety for deeply nested paths. The explicit check provides compile-time narrowing.
type Config = { api?: { endpoint?: string } } | undefined;
function getEndpoint(config: Config): string {
const endpoint = config?.api?.endpoint;
if (endpoint) {
return endpoint;
}
return "default";
}This version extracts the optional chain result to a variable, then checks the variable directly. The check narrows the variable's type from string | undefined to string. The pattern separates runtime safety from type narrowing, letting each mechanism operate independently.
For related patterns in TypeScript configuration, see globalThis typing in TypeScript and function overload techniques.

When Optional Chaining Is Safe and When It Lies to the Compiler
Optional chaining works correctly in contexts that do not require type narrowing. Extracting values, calling methods conditionally, and handling deeply nested structures all benefit from ?. without introducing type safety issues.

Safe patterns include assignment, return values, and function arguments. These contexts accept T | undefined as a valid type. The optional chain produces the correct type for the context.
type User = { profile?: { avatar?: string } };
function getAvatar(user: User): string | undefined {
return user.profile?.avatar;
}The function signature declares the return type as string | undefined. The optional chain produces exactly that type. No narrowing occurs and none is needed. The caller receives the value or undefined, handling both cases explicitly.
Unsafe patterns occur when the developer expects the check to prove existence. Conditionals, early returns, and ternary expressions all fall into this category when they gate subsequent operations.
type Data = { values?: number[] };
function sum(data: Data): number {
// Unsafe: data.values might be undefined inside the branch
if (data.values?.length > 0) {
return data.values.reduce((a, b) => a + b, 0);
}
return 0;
}The check data.values?.length > 0 does not narrow data.values to a defined array. The compiler treats data.values as number[] | undefined inside the branch. The reduce call requires a defined array, causing a type error.
| Context | Optional Chaining Safety | Requires Explicit Guard |
|---|---|---|
| Assign to variable | Safe | No |
| Return from function | Safe | No |
| Pass as argument | Safe | No |
| Conditional branch | Unsafe | Yes |
| Early return guard | Unsafe | Yes |
| Ternary condition | Unsafe | Yes |
| Array/object spread | Unsafe | Yes |
The table shows the split between extraction contexts and narrowing contexts. Extraction accepts T | undefined as a valid result. Narrowing expects the check to eliminate undefined from the type. Optional chaining serves the first need but not the second.
Method calls through optional chaining work safely when the method might not exist. The TypeScript 3.7 playground example demonstrates optional calls for callbacks that might be undefined.
async function makeRequest(url: string, log?: (msg: string) => void) {
log?.(`Request started at ${new Date().toISOString()}`);
const result = await fetch(url).then((r) => r.json());
log?.(`Request finished at ${new Date().toISOString()}`);
return result;
}The optional call log?.(...) checks if log is defined before calling it. This pattern is safe because the call site does not require type narrowing. The function either calls the logger or does nothing. The return value of the optional call is void | undefined, which the function ignores.
Short-circuiting behavior compounds the issue. The TypeScript 3.7 release notes explain that short-circuiting is limited to the chained expression. An optional chain followed by other operations continues executing those operations even when the chain returns undefined.
let result = foo?.bar / someComputation();The example divides the optional chain result by a function call. When foo is undefined, the chain returns undefined, but someComputation() still executes. The division produces NaN. Developers expect the entire expression to short-circuit, but only the property access stops. This behavior does not cause type errors, but it violates runtime expectations when developers treat ?. as a broader safety mechanism.
Frequently Asked Questions
Why does TypeScript still consider a value undefined after checking with optional chaining?
Optional chaining performs a runtime check but does not provide a type guard. The compiler sees the expression as producing T | undefined and does not narrow the base type. Explicit checks like if (value) or if (value !== undefined) provide discrete narrowing points that the type system tracks through control flow.
Can I use optional chaining with discriminated unions?
Optional chaining works for accessing discriminant properties, but it does not narrow the union when the base type includes undefined. Check the base value exists first with if (shape), then access the discriminant. This pattern separates the null check from the discriminant check, allowing TypeScript to narrow the union correctly.
Does the in operator work with optional chaining?
The in operator checks if a property exists on an object and narrows the type to unions containing that property. It does not combine directly with optional chaining. Use if (value && "property" in value) to check the value exists before testing for the property. The two checks provide separate narrowing steps that the compiler recognizes.
What is the difference between foo?.bar and foo && foo.bar for type narrowing?
The optional chain foo?.bar returns T | undefined without narrowing foo. The explicit check foo && foo.bar narrows foo to a defined value in the left-hand side, then accesses bar safely. TypeScript tracks the control flow for explicit checks but not for optional chains. Use explicit checks when the subsequent code requires a narrowed type.
How do I combine optional chaining with type guards?
Extract the optional chain result to a variable, then apply a type guard to the variable. For example, const value = foo?.bar; if (value) narrows value to a defined type. This pattern separates the runtime safety of optional chaining from the compile-time narrowing of explicit checks. The variable holds the extracted result, and the guard narrows its type.
Conclusion
Optional chaining provides runtime safety for deeply nested property accesses but does not narrow types in TypeScript's control flow analysis. The ?. operator returns T | undefined without updating the base value's type, forcing developers to combine optional chaining with explicit null checks, the in operator, or type predicates to restore type safety in conditional branches. Discriminated unions, array length checks, and method calls all require explicit guards when the code depends on narrowed types. For linting and formatting patterns that complement TypeScript's type system, see Biome and oxlint comparison. Extracting optional chain results to variables and testing those variables directly separates runtime convenience from compile-time correctness, letting each mechanism serve its intended role.