Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript TS2339: Property does not exist on type

TS2339 means the declared type has no such member. Declare the shape, narrow unions and guard unknown values instead of casting at the read.

~5 min readTypeScript
#typescript#ts2339#type-narrowing#strict-mode
Bold white headline reading TS2339 with a TypeScript object crate missing an amber property slot beside a cyan interface plate.

Introduction & Quick Summary

The compiler stops on a line that looks perfectly fine at runtime:

code
src/api/user.ts:12:18 - error TS2339: Property 'name' does not exist on type '{}'. 12 return response.data.name; ~~~~

Quick answer: TS2339 is a statement about the declared type, not about the value. Give the value a type that actually has the property, or narrow it until TypeScript can prove the property exists.

ts
type ApiUser = { id: string; name: string }; async function getUser(): Promise<ApiUser> { const response = await fetch("/api/user"); return (await response.json()) as ApiUser; // boundary cast, validated by a schema in real code }

The error follows one rule: property access is legal only when every member of the receiver's type declares that property. {} declares nothing, unknown declares nothing, and a union declares only what all members share. any disables the rule, which is why the error often appears the moment a codebase enables strict or replaces any with a real type.

Three variants cover most reports. Property 'x' does not exist on type '{}' usually means an untyped JSON response or an empty object literal. Property 'x' does not exist on type 'A | B' means narrowing is missing. Property 'x' does not exist on type 'never' means an earlier guard already eliminated every member, so the type collapsed.

Core Mechanics, Signatures & Reproducible Setup

Reproduce each variant in one file:

bash
mkdir ts2339 && cd ts2339 npm init -y >/dev/null && npm i -D typescript npx tsc --init --strict cat > demo.ts <<'TS' const payload = {}; // {} console.log(payload.name); // TS2339 on {} type Cat = { meow(): void }; type Dog = { bark(): void }; function speak(pet: Cat | Dog) { pet.meow(); // TS2339: not on Dog } const el = document.querySelector("#email"); // Element | null el.value; // TS2339 on Element, and possibly null TS npx tsc --noEmit

TypeScript resolves a.b by looking for b on the type of a. Object literals get a widened type: { id: 1 } is { id: number }, but {} stays {} and carries no index signature. Interfaces are open to declaration merging, type aliases are closed, and neither one gains properties from runtime assignment.

Receiver typeobj.nameReason
{ name: string }alloweddeclared on the type
{ name?: string }allowed, string or undefinedoptional property is declared
{}TS2339no members declared
unknownTS2339 (or TS18046)must be narrowed first
anyallowedchecking disabled
Cat or DogTS2339 unless both declare itunion exposes the intersection of members
Record<string, string>allowedindex signature covers every key
neverTS2339no members exist at all

Assignment is different from access. const p: { name: string } = {} fails with TS2741 (missing property), while reading ({} as {}).name fails with TS2339. Keeping the two apart saves time, because the fix for one is not the fix for the other.

Key Comparison Table

StrategyExampleCompile safetyRuntime effectUse when
Declare the propertytype U = { name: string }fullnonethe shape is known
Narrow the unionif ("meow" in pet)fullnonemembers differ
Type guard functionisUser(x): x is Userfullone check per calldata crosses a boundary
Index signatureRecord<string, string>weaknonekeys are dynamic
Generic constraint<T extends HasName>fullnonereusable helper
Assertionvalue as Usernonenonelast resort, boundary only
Non-null assertionel!.valuenonethrows if nullelement always exists

Errors that look similar but come from different checks:

MessageMeaningTypical origin
TS2339 property does not existmember missing on typeuntyped JSON, union, empty object
TS18046 value is of type unknownreceiver not narrowedcatch (e), JSON.parse
TS7053 implicit any indexdynamic key on typed objectobj[key] with string
TS2741 property missing in typeobject literal incompleteconfig object
TS2551 did you meantypo in member namemisspelled property

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Unions: narrow before you read

ts
type Result = | { ok: true; data: { id: string; name: string } } | { ok: false; error: string }; function label(r: Result) { if (r.ok) return r.data.name; // narrowed to the success member return r.error; }

A discriminant such as ok is the cheapest narrowing. in works when members have no shared literal, and instanceof works for classes. Type assertions inside a union branch are a smell: if the compiler cannot follow the discriminant, the union is usually shaped wrong.

2. catch variables are unknown

With useUnknownInCatchVariables (on under strict since TypeScript 4.4), catch (err) gives unknown:

ts
try { await save(); } catch (err) { console.error(err.message); // TS2339 if (err instanceof Error) console.error(err.message); // ok }

Custom error fields need a guard: function isDbError(e: unknown): e is DbError { return e instanceof DbError }. Never cast straight to Error, because a rejected string has no message and the catch block itself throws.

3. JSON boundaries: validate, do not cast

response.json() returns any in the DOM lib, so the cast to a real type moves the failure from compile time to the first missing field. Validate once at the boundary and return a typed value:

ts
import { z } from "zod"; const User = z.object({ id: z.string(), name: z.string() }); type User = z.infer<typeof User>; export async function loadUser(): Promise<User> { const res = await fetch("/api/user"); return User.parse(await res.json()); }

When the payload shape is unclear, paste it into the JSON formatter and compare two responses with the text diff tool; a field that appears only on some responses belongs in an optional type, not in a cast.

4. Dynamic keys and index signatures

ts
type Env = Record<string, string>; const env: Env = { NODE_ENV: "production" }; env.PORT; // allowed, but no typo protection env["PORRT"]; // allowed, silently undefined function pick(obj: Record<string, number>, key: string): number { return obj[key]; // number, but may be undefined at runtime }

Turn on noUncheckedIndexedAccess to get number | undefined from every index read and handle the miss. noPropertyAccessFromIndexSignature then forces bracket syntax for signature keys, which makes the untyped access visible in review. For a fixed set of keys, declare the keys explicitly and derive them: type EnvKey = "NODE_ENV" | "PORT" with Record<EnvKey, string>.

5. Generic constraints instead of assertions

ts
function firstLength<T>(items: T[]): number { return items[0].length; // TS2339: Property 'length' does not exist on type 'T' } function firstLength<T extends { length: number }>(items: T[]): number { return items[0].length; // ok }

The constraint is documentation: callers must pass something with length. keyof solves the sibling case: function get<T, K extends keyof T>(obj: T, key: K): T[K] returns the exact member type, so get(user, "name") is string while get(user, "nmae") is a compile error.

6. DOM types and stale libraries

document.querySelector returns Element | null, and Element has no value, checked, href or dataset entry for every case:

ts
const input = document.querySelector<HTMLInputElement>("#email"); if (!input) throw new Error("missing #email"); input.value = "a@b.c"; const form = document.querySelector("form"); form?.addEventListener("submit", (event) => { const target = event.target as HTMLFormElement; // target is EventTarget new FormData(target); });

Two more sources: @types/* packages that lag behind the library version produce TS2339 on new APIs, and module augmentation is needed for framework-added members such as req.user on Express Request. Augment the module once in a .d.ts file rather than casting at every call site.

Common Compilation/Runtime Mistakes & Version Gotchas

Silencing with as any at the access point. The error moves to the caller and returns as Cannot read properties of undefined in production. Cast at the data boundary, not at the read.

Assuming optional chaining declares the property. obj?.name still fails when name is not on obj's type. Optional chaining handles null and undefined receivers, not missing members.

Object.keys returns string[]. Object.keys(config).forEach((k) => config[k]) fails on a typed object without an index signature; iterate Object.entries or type the key as keyof typeof config.

in narrowing behaves differently across versions. TypeScript 4.9 widened in narrowing to properties not listed on the type, so older compilers report TS2339 where a current one narrows. Pin the compiler version in CI so two developers see the same diagnostics.

Property access on class instances versus the class itself. User.name is TS2339 because name is an instance member; the value is user.name. Static members are the reverse. This also explains this errors in callbacks extracted from methods.

Literal types are not widened inside as const. const cfg = { port: 3000 } as const gives readonly port: 3000; a later cfg.port = 8080 is TS2339 rather than an assignment error, which hides the real problem.

Version notes. noUncheckedIndexedAccess changes the type of every index read; noPropertyAccessFromIndexSignature (TypeScript 4.2) rejects dot access on index signatures; exactOptionalPropertyTypes (4.4) stops undefined from satisfying prop?: T; satisfies (4.9) checks a value against a type without widening it, which is usually the right tool for config objects that must keep literal types.

Reference material: narrowing and noImplicitAny.

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.