What is getElementById's return type and the check needed for .value?
Tests strict null awareness: getElementById returns HTMLElement or null, so null-check first. Strong answers note HTMLElement lacks .value, requiring narrowing to HTMLInputElement. Red flag: assuming a valid element is always returned.
WHAT THIS TESTS: This tests strict null awareness and knowledge of the DOM type hierarchy in TypeScript. The interviewer is checking whether you know that browser APIs can return null and that generic element methods return base interface types rather than specific element types. It also reveals whether you rely on type assertions or actually perform runtime checks.
A GOOD ANSWER COVERS: First, state that document.getElementById returns HTMLElement or null as defined in lib.dom.d.ts. Second, explain that you must guard against null with a truthiness check, optional chaining, or explicit comparison before accessing members. Third, because HTMLElement is the base interface for all elements and lacks input-specific properties, you must narrow the type to HTMLInputElement to access .value safely. This can be done with instanceof HTMLInputElement or a type assertion after the null check. Fourth, emphasize that combining the null guard and type narrowing in sequence is the only fully safe approach.
COMMON WRONG ANSWERS: Claiming the return type is HTMLInputElement or null is wrong because getElementById always returns the base HTMLElement type. Forgetting the null check entirely signals poor understanding of strictNullChecks. Accessing .value after only a null check without narrowing is also wrong because TypeScript will report that .value does not exist on HTMLElement. Using a non-null assertion operator to force access is another red flag because it ignores both the null possibility and the wrong element type.
LIKELY FOLLOW-UPS: The interviewer may ask if optional chaining alone is sufficient, which leads to discussing that it only solves the null problem, not the missing .value on HTMLElement. They might ask whether querySelector is better here, allowing you to explain that querySelector with a generic type argument of HTMLInputElement preserves nullability while returning the correct specific type. They could also ask about writing a reusable type guard function to encapsulate the narrowing logic.
ONE CONCRETE EXAMPLE: const el = document.getElementById("my-input"); if (el !== null && el instanceof HTMLInputElement) { console.log(el.value); } Or using querySelector with a generic type argument of HTMLInputElement: const input = document.querySelector("#my-input"); if (input) { console.log(input.value); } where input is already typed as HTMLInputElement or null.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.