TypeScript Compiler Diagnostics
TS2339: Missing property on a union
A union permits only operations safe for every possible member until narrowed. Here only strings have length; use a typeof guard, and handle the numeric alternative explicitly. A missing property can also indicate a typo or an incorrect declaration. Baseline: TypeScript 5.8.3 with the shown configuration. Diagnose the reported location and nested message before applying a fix; other causes may require a different correction. The first project is intentionally invalid; create the corrected project separately. Neither example requires disabling strict checking.
Formal Syntax & Structure
typescript syntaxtypescript
TS2339 (compiler diagnostic code, not TypeScript syntax)Working Example
Example Snippettypescript
// INTENTIONALLY INVALID — reproduce// File: tsconfig.json (omit this label){ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "types": [], "lib": [ "ES2022", "DOM" ], "noEmitOnError": true, "outDir": "dist" }, "files": [ "main.ts" ]}
// File: main.ts (omit this label)function size(value: string | number) { return value.length; }console.log(size("abc"));
// Run: tsc -p . --pretty false// Expected: TS2339; no emitted main file.
// CORRECTED PROJECT// File: tsconfig.json (omit this label){ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "types": [], "lib": [ "ES2022", "DOM" ], "noEmitOnError": true, "outDir": "dist" }, "files": [ "main.ts" ]}
// File: main.ts (omit this label)function size(value: string | number) { return typeof value === "string" ? value.length : 1; }console.log(size("abc"), size(9));
// Run: tsc -p . --pretty false// Expected: no diagnostics.// Run: node dist/main.js// Expected stdout: 3 1