Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Archives
Tags
- db
- java
- do while
- vue
- mysql
- float
- CSS
- 자료형
- 자바 기초
- JS
- 웹디자인 기능사
- 조건문
- Break Continue
- Heidi
- To Do List
- 자바
- 로또 번호 생성
- 연산자
- 전자정부프레임워크
- clear
- react
- DropDown
- overflow
- 자바 환경변수
- Openjdk
- switch
- HTML
- position
- javascript
- Display
- Today
- Total
잠온다
TS) Typescript로 HTML 변경 및 조작할 때 주의점 본문
1. 예제1
// tsconfig.json에서 strictNullCheck 옵션 키고 시작
<h1 id="title">제목</h1>
let title = document.querySelector('#title');
title.innerHTML = '타이틀';
// typescript에선 error 발생
// title이라는 변수가 null일 수 있기 때문
// 1.
if (title != null) { title.innerHTML = '타이틀'; } // narrowing 해주면 해결
// 2.
if (title instanceof HTMLElement) { title.innerHTML = '타이틀'; } // 더 좋은 방법
// 3.
let title = document.querySelector('#title') as HTMLElement; // or Element
title.innerHTML = '타이틀'; // 좋은 방법은 아님
// 4.
let title = document.querySelector('#title');
if (title?.innerHTML != undefined) { title.innerHTML = '타이틀'; }
// js 신문법. 왼쪽에 있는 object에 .innerHTML이 존재하면 그거 사용해주고 아니면 undefined 해주라.
// 5. 그냥 strict false 해줘도 된다.
2. 예제2
<a id='link' href='naver.com'></a>
let link = document.querySelector('#link');
if (link instanceof HTMLElement) { link.href = 'https://kakao.com'; } // error
// HTMLElement라는 타입은 href 라는 속성이 없기 때문
let link = document.querySelector('#link');
if (link instanceof HTMLAnchorElement) { link.href = 'https://kakao.com'; } // good
// a : HTMLAnchorElement
// img : HTMLImageElement
// h1~h6 : HTMLHeadingElement ...
3. 예제3
let btn = document.querySelector('#btn');
btn.addEventListener('click', function() { console.log('hi'); });
// error - btn이라는 변수는 null일 수 있음
// 정석
let btn = document.querySelector('#btn');
if (btn instanceof HTMLButtonElement) {
btn.addEventListener('click', function() { console.log('hi'); });
}
// optional chaining (2020년 이후 브라우저들은 사용 가능)
let btn = document.querySelector('#btn');
btn?.addEventListener('click', function() { console.log('hi'); });
4. 예제4
<a class='naver' href='naver.com'>link</a>
<a class='naver' href='naver.com'>link</a>
<a class='naver' href='naver.com'>link</a>
let linkArr = document.querySelector('.naver');
if (linkArr.isArray) { // array check 안해주면 linkArr.length에서 에러
for (let i = 0; i < linkArr.length; i++) {
if (linkArr[i] instanceof HTMLAnchorElement) {
linkArr[i].href = 'https://kakao.com';
}
}
}
'Typescript' 카테고리의 다른 글
TS) Enum, typeof, keyof (0) | 2023.01.01 |
---|---|
TS) Literal Types / as const (0) | 2022.05.28 |
TS) type alias / readonly / object 옵션 / type 키워드 합치기 (0) | 2022.05.28 |
TS) 함수 타입 지정 및 Type Narrowing (0) | 2022.05.28 |
TS) 기본 타입 및 union, any, unknown type (0) | 2022.05.28 |
Comments