"매 DOM API 의 untyped boundary 의 TypeScript narrowing 의 적용". 매 querySelector 의 default Element | null 위 의 generic + instanceof + assertion. 2026 의 strict null checks + satisfies + lib.dom.d.ts 의 mainstream type ergonomics.
매 핵심
매 Type narrowing tools
Generic param: querySelector<HTMLInputElement>(...) — runtime check 의 X, 매 assertion 만.
instanceof: 매 runtime check + narrow.
Type guard function: function isInput(el): el is HTMLInputElement.
querySelector 의 null 의 always 가능 — 매 explicit check.
getElementById 의 same — HTMLElement | null.
as! non-null assertion 의 last resort — 매 prefer guard.
매 응용
Form value 추출 + validation.
Dynamic widget hydration (서버 HTML 위 의 JS enhance).
Custom element / Web Component 의 typed access.
💻 패턴
querySelector with generic
// 매 generic 의 assertion 만 — 매 null 의 still 가능
constinput=document.querySelector<HTMLInputElement>('#email');if(!input)thrownewError('email input missing');input.value;// 매 narrowed to HTMLInputElement
instanceof guard
constel=document.getElementById('email');if(elinstanceofHTMLInputElement){el.value='test@example.com';// 매 narrowed
}else{thrownewError('not an input');}
Custom type guard
functionisInput(el: Element|null):elisHTMLInputElement{returnelinstanceofHTMLInputElement;}functiongetValue(selector: string):string{constel=document.querySelector(selector);if(!isInput(el))thrownewError(`${selector} is not input`);returnel.value;}
classMyToggleextendsHTMLElement{toggle() {this.toggleAttribute('open');}}customElements.define('my-toggle',MyToggle);declareglobal{interfaceHTMLElementTagNameMap{'my-toggle':MyToggle;}}constt=document.querySelector('my-toggle');// 매 typed as MyToggle | null
t?.toggle();