Frontend/Error

[react18 + typescript] document.getElementById("root")

khakhalog 2023. 1. 4. 00:12

document.getElementById("root")

⁉️ 문제 원인

1. getElementById는 다음과 같이 정의되어 있으며 null값을 반환할 수 있다.

getElementById(elementId: string): HTMLElement | null;

-> Typescript의 타입 추론 결과에서는 null 값과 같은 알 수 없는 타입에 대한 정보가 나타날 경우 Type assertion(타입 단언)을 통해 타입을 지정해줄 수 있다.

 

✅ 해결 방안

Type Assertion

컴파일러에게 변수의 타입을 알려주는 메커니즘으로, TypeScript의 타입 추론 결과가 실제와 다르게 추론되었다 생각하는 경우 사용할 수 있다. 또한, Type Assertion은 컴파일러에 의해 제거되기 때문에 코드의 런타임 동작에 영향을 미치지 않는다.

1) as

- type Assertion 구문 중 하나이며 아래와 같이 사용한다.

const container = document.getElementById("root") as HTMLElement;

2) angle braket 구문

- 꺾쇠 괄호(<>)로 HTML 태그모양과 같다.

const container = <HTMLElement>document.getElementById("root");

주의할점은 angle braket은 HTML 태그와 형태가 동일하여 .jsx, .tsx 파일에서는 사용할 수 없다.

 


+ 이외에도 null 값 반환시 error throw하도록 처리해줄 수 있다고 한다.

const rootElement = document.getElementById("root");
if (!rootElement) throw new Error("Failed to find the root element");
const root = ReactDOM.createRoot(rootElement);