This TypeScript compile error (TS18047) is reported when you try to access a property or call a method on a value whose type includes null. TypeScript's strict null checks (enabled by strictNullChecks or strict: true) require you to explicitly handle the null case before using the value.
Why it happens
- •DOM query methods like querySelector() return Element | null, and the null case is not handled before accessing properties.
- •An optional function parameter or object field that may be null or undefined is used without a guard.
- •A value from an API or database that can legitimately be null is accessed directly.
- •A function's return type is T | null and the caller does not check for null before using the result.
Examples
Code that triggers the error
const input = document.querySelector<HTMLInputElement>("#email");
console.log(input.value);Error output
error TS18047: 'input' is possibly 'null'.
How to fix it
Add an explicit null check (if (value !== null)) before accessing properties. Use optional chaining (?.) for concise safe access. Use the non-null assertion operator (!) only when you are absolutely certain the value cannot be null at runtime, as it bypasses the type check. Enable strictNullChecks in your tsconfig to surface these issues early.
Fixed code
const input = document.querySelector<HTMLInputElement>("#email");
// Option 1: narrow with a null check
if (input !== null) {
console.log(input.value);
}
// Option 2: non-null assertion (only use when you are certain)
const value = input!.value;
// Option 3: optional chaining
console.log(input?.value);Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free