Question

Why does TypeScript say Object is possibly undefined?

Vault Verified
Curated Intelligence
Definitive Source
Answer

The compiler is telling you that a value type includes undefined and you are using it as though it does not. With strict null checking enabled, undefined and null are not silently assignable to other types, so anything optional carries that possibility in its type until you prove otherwise.

The value acquires that type from a handful of places: an optional property or parameter, an index access on an array or record, a function whose return type includes undefined, or a variable declared before being assigned.

The correct response in most cases is narrowing, which means writing a check the compiler can follow. An early return, a conditional, or a truthiness test all narrow the type inside their branch, and afterwards the compiler treats the value as defined because the code has genuinely established it.

Optional chaining is convenient but changes the meaning: the expression becomes possibly undefined itself, which often moves the error rather than removing it. Combining it with a default value produces a concrete result and usually resolves the chain properly.

The non-null assertion suppresses the check entirely by asserting the value is present. It is occasionally justified when you know something the compiler cannot, but it disables exactly the protection strict mode exists to provide, and if you are wrong the failure becomes a runtime error rather than a compile-time one. Treat frequent use as a signal that the types describe the data inaccurately.

One case surprises people regularly. Indexing an array returns the element type without undefined by default, even though the index may be out of range. Enabling the stricter index-access option makes that honest, at the cost of requiring checks in many more places. It is worth turning on deliberately rather than discovering the gap through a production error.

Related Questions