TS 중의 DOM 요소 및 이벤트 유형 선언

1. HTMLElement와 Element

<div id="divClick"></div>
const divElement = document.getElementById('divClick');
const divElement2 = document.querySelector('#divClick');

HTMLElement HTMLElement는 HTML 문서中の 특정 요소의 구체적인 유형입니다. 이 유형은 모든 HTML 요소의 공통 속성과 방법(예: CSSStyleDeclaration, EventTarget)를 포함합니다.

Element Element는 HTMLElement의 기본 유형이며, 문서中の 어떠한 유형의 마크업 요소(예: div, span, p 등)를 모두 포함합니다. Element 유형은 가장 기본적인 속성(예: tagName, attributes)및 방법(예: getAttribute(), setAttribute())만을 포함합니다.

HTMLElement와 Element의 차이

  • Element는 모든 문서 객체 아래의 모든 객체가 상속하는 일반적인 기본 유형입니다.
  • HTMLElement는 Element를 확장하여 HTML 요소의 특정 속성과 방법을 추가합니다.

예를 들어, TypeScript의 lib.dom.d.ts 파일에서 HTMLElement는 다음과 같이 정의됩니다:

interface HTMLElement extends Element, ElementCSSInlineStyle, ElementContentEditable, GlobalEventHandlers, HTMLOrSVGElement {
    // ... 그외의 속성과 방법
    click(): void;
    addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
    // ... 그외의 이벤트리스너 방법
}

2. 특정 DOM 요소 유형 선언

하나의 요소를 선택할 때마다 HTMLElement로 타입을 지정할 수 있지만, 때로는 더 구체적인 유형이 필요합니다. 예를 들어:

<input type="text" value="hello">
const input = document.querySelector('input[type=text]') as HTMLElement;
console.log(input!.value); // TypeScript 오류: 'value' 속성 없음

이런 경우 HTMLInputElement로 더 구체적인 유형을 지정해야 합니다.

const input = document.querySelector('input[type=text]') as HTMLInputElement;
console.log(input.value); // 정상 작동

HTMLInputElement는 HTMLElement를 확장하며, input 요소만을 위한 특정 속성(예: value, type, placeholder)을 포함합니다.

3. 이벤트 유형

3.1 이벤트 유형 소개

Event 인터페이스는 DOM 이벤트의 기본 정보를 포함하며, 모든 유형의 이벤트는 이 인터페이스를 상속합니다.

예를 들어, 사용자 정의 이벤트를 확장하는 방법:

interface CustomEvent extends Event {
    data: string;
}

const handleCustomEvent = (e: CustomEvent) => {
    console.log(e.data);
};

3.2 일반적인 이벤트 유형

TypeScript의 lib.dom.d.ts 파일에서 정의된 주요 이벤트 유형들:

interface GlobalEventHandlersEventMap {
    "click": MouseEvent;
    "change": Event;
    "mouseover": MouseEvent;
    "keydown": KeyboardEvent;
    // ... 그외의 이벤트 유형
}

예를 들어, Vue.js나 React에서 이벤트를 처리할 때:

<div @click="handleClick"></div>
const handleClick = (e: MouseEvent) => {
    // 이벤트 처리 로직
};

3.3 React 중의 이벤트 유형

React는 자체적인 합성 이벤트를 통해 이벤트를 처리합니다. 주요 이벤트 유형들:

MouseEvent<HTMLDivElement> // 마우스 이벤트
KeyboardEvent<HTMLDivElement> // 키보드 이벤트
ChangeEvent<HTMLInputElement> // 입력 이벤트
DragEvent<HTMLDivElement> // 드래그 앤 드롭 이벤트

예를 들어:

const handleDragStart = (event: React.DragEvent<HTMLDivElement>) => {
    // 드래그 시작시의 로직
};

태그: TypeScript DOM Event React

5월 29일 02:04에 게시됨