TypeScript type casting

강정우·2023년 6월 14일
0

TypeScript

목록 보기
18/22
post-thumbnail

type casting

<body>
	<input id="message-output">hi</input>
</body>

  • 위와 같은 코드가 있다고 해보자. => 이때 .value를 인식을 못 한다 왜? => 사용자는 input값으로 잡아놨지만 TS는 이게 input값이 아닌 HTMLElement로만 알고 있기 때문이다.
    그럼 어떻게 해결해야할까?

<>

const paragraph = <HTMLInputElement>document.getElementById('message-output')!;
paragraph.value = 'Hi there!';
  • 바로 사용하고자 하는 변수 앞에 <> 키워드로 타입을 다시 선언해버리면 된다. 물론 TS에서 이 DOM 태그를 인식하고 자동완성까지 제공하는 이유는 앞서 배운 tsconfig에 lib 속성에 'DOM' 이 default로 추가되어있기 때문이다.

  • 하지만 이는 React를 사용한다면 에러가 발생할 수 있는데 React에서 <컴포넌트>는 하나의 자식 또는 부모 컴포넌트로 사용되기 때문에 이와같은 type casting은 문법의 중복을 야기한다. 따라서 React 한정으로 다른 타입 캐스팅을 지원한다.

type casting in React (as)

  • 바로 as 키워드이다.
const paragraph = document.getElementById('message-output')! as HTMLInputElement;
paragraph.value = 'Hi there!';
const paragraph = document.getElementById('message-output');
if (paragraph) {
    (paragraph as HTMLInputElement).value = 'Hi there!';
}
  • 물론 이렇게 쓸데없이 길게 사용도 가능하다.
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글