TypeScript

[TypeScript] Strict, HTML 조작할 때 주의점

최성2 2022. 2. 19. 22:13

 

✅ tsconfing.json 에서 엄격한 유형 검사 설정하기

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true 👈 //모든 엄격한 유형 검사 옵션 활성화
  }
}

 

*엄격한 유형 검사 옵션

"noImplicitAny": true
//명시적이지 않은 'any' 유형으로 표현식 및 선언 사용 시 오류 발생

"strictNullChecks": true
//엄격한 null 검사 사용

"strictFunctionTypes": true
//엄격한 함수 유형 검사 사용

"strictBindCallApply": true
//엄격한 'bind', 'call', 'apply' 함수 메서드 사용

"strictPropertyInitialization": true
//클래스에서 속성 초기화 엄격 검사 사용

"noImplicitThis": true
//명시적이지 않은 'any'유형으로 'this' 표현식 사용 시 오류 발생

"alwaysStrict": true
//엄격모드에서 구문 분석 후, 각 소스 파일에 "use strict" 코드를 출력

 


 

 "strictNullCheck": true 

HTML을 조작할 때 null 인지 아닌지 캐치할 수 있기 때문에, 도움이 된다

 

 

strict 옵션(null 체크 설정)을 켜주고 타입스크립트로 HTML를 조작하면 에러가 난다

<body>
    <h4 id="title">안녕하세요</h4>
    <a href="naver.com" class="link">링크</a>
    <button id="button">버튼</button>
</body>
let title = document.getElementById('title')

title.innerHTML = '반가워요'
//에러 발생

 

타입이 Element | null(애매한 타입) 이기 때문에 에러가 발생하는데, 해결 방법은 다음과 같다

 

 

1. narrowing

let title = document.getElementById('title')

if(title != null) { 👈
  title.innerHTML = '반가워요'
}

 

 

✅ 2. instanceof 를 이용한 narrowing

: 가장 많이 사용하는 방법

let title = document.getElementById('title')

if(title instanceof HTMLElement) { 👈
  title.innerHTML = '반가워요' 
}

 

 

3. assertion

: 비상시에만 사용

let title = document.getElementById('title') as HTMLElement 👈

title.innerHTML = '반가워요'

 

 

4. optional chaining 을 이용한 narrowing

: .innerHTML이 존재하면 그거 써주고, 없으면 undefined를 뱉어라

let title = document.getElementById('title')
if(title?.innerHTML != undefined) { 👈
  title.innerHTML = '반가워요'
}

 

 

5. strict 설정 끄기 

: null 체크가 귀찮으면 설정을 꺼라

 


 

a태그 href 변경하기

<body>
    <h4 id="title">안녕하세요</h4>
    <a href="naver.com" class="link">링크</a>
    <button id="button">버튼</button>
</body>
let link = document.querySelector('.class')

link.href = 'kakao.com'
//에러 발생(2)

 

 

첫 번째 에러 고치기(narrowing 사용)

let link = document.querySelector('.class')

if(link instanceof HTMLElement) { 👈
  link.href = 'kakao.com'
}

 

두 번째 에러 고치기(정확한 타입 명칭 달아주기)

let link = document.querySelector('.class')

if(link instanceof HTMLAnchorElement) { 👈
  link.href = 'kakao.com'
}

 

 

✅ 타입스크립트가 제공하는 HTML 기본 타입들이 존재한다

ex.

a 태그:  HTMLAnchorElement 

img 태그:  HTMLImageElement 

h1 태그:  HTMLHeadingElement 

button 태그:  HTMLButtonElement 

 

보통 자동완성되기 때문에 전부 외울 필요는 없다.

 

 

 

Ref

https://codingapple.com/course/typescript-crash-course/

 

빠르게 마스터하는 타입스크립트 - 코딩애플 온라인 강좌

  누구나 마음 한켠엔 나만의 웹서비스를 만들고 싶어합니다. 프론트엔드는 어찌저찌 하겠는데 서버 만드는게 어렵고 귀찮다고요? 그렇다면 Firebase를 쓰십시오.   구글이 웹서버를 대신 만들어

codingapple.com

 

'TypeScript' 카테고리의 다른 글

[TypeScript] Rest, Destructuring Type  (0) 2022.02.25
[TypeScript] Interface  (0) 2022.02.23
[TypeScript] Function, Method alias Types  (0) 2022.02.18
[TypeScript] Literal Type  (0) 2022.02.17
[TypeScript] Type Alias, readonly, extend  (0) 2022.02.16