In this lesson, you selected door-check’s search box so the checker knows it’s an input, and you put the LST- prefix in it with an instanceof check that runs as a real test in the browser.
Key Points
- The checker reads
src/main.tsbefore anything runs and never opensindex.html. From a class selector such as".ref-search", all it has is a string, sodocument.querySelector()givesElement | null. Elementis the DOM library’s type for any element at all, a heading, a list or an input. It only promises what every element has, so it has novalue. The first draft reports two errors on one line: TS18047,'search' is possibly 'null', and TS2339,Property 'value' does not exist on type 'Element'.- A tag name tells the checker more:
document.querySelector("input")givesHTMLInputElement | null. But a page often has more than one input, so keep the class and check the element instead. - Besides the type, the browser has a real class named
HTMLInputElement, and every input is an instance of it.search instanceof HTMLInputElementis false fornull, so one test covers both errors. - The checker follows it branch by branch:
Element | nullabove theif,HTMLInputElementinside it, andElement | nullagain in theelsebranch, because a false test means nothing matched or the element isn’t an input.Elementisn’t a union with an input member, so there’s nothing to take out. - The types at each line were the checker’s own, worked out from the code. None of these labels is written in the file. So Vite has no type syntax to remove, and the
instanceoftest runs in the browser as written. If the search box goes missing, theelsebranch logsNo booking-reference input: null. - A type argument,
document.querySelector<HTMLInputElement>(".ref-search"), claims the element is an input, but the result is stillHTMLInputElement | null, so you still need a null check. The claim is removed before the code runs, so nothing checks it.
Final Code
The page keeps its search box as it was, and only the end of src/main.ts changes. The selection stays on the class, and the instanceof check does the rest: it rules out null and any element that isn’t an input, for the checker and in the browser alike. The search box in index.html: