TypeScript Compiler Diagnostics
TS18047: Value is possibly null
A nullable union permits null, which has no length property. A guard excludes null on the branch that reads the string. The fallback is an explicit product decision, not an assertion that the value exists. Optional chaining is useful when an undefined result is appropriate. Baseline: TypeScript 5.8.3 with the shown configuration. Reproduce in one directory and create the corrected project in another. The diagnostic can have other causes; inspect its location and message before choosing a correction. Both projects keep strict checking enabled.
Formal Syntax & Structure
typescript syntaxtypescript
TS18047 (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(text: string | null) { return text.length; }
// Run: tsc -p . --pretty false// Expected: TS18047; no output emitted.
// CORRECTED PROJECT — separate directory// 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(text: string | null) { return text === null ? 0 : text.length; }console.log(size("cat"), size(null));
// Run: tsc -p . --pretty false// Expected: no diagnostics.// Run: node dist/main.js// Expected stdout: 3 0