변수에 타입 지정하기
타입스크립트의 타입은 primitive 타입과 object타입으로 나눌 수 있다. primitive 타입은 string, number, boolean 등 원시 타입이고, object타입은 객체 그 자체는 모든 것이 타입이 될 수 있기 때문에 수 없이 많다.
type Store = {
currentPage :number,
feeds :NewsFeed[]
}
type NewsFeed = {
id :number,
comments_count :number,
url :string,
user :string;
time_ago :string,
points :number,
title :string,
read? :boolean
}
const container: HTMLElement | null = document.querySelector('#root');
const ajax :XMLHttpRequest = new XMLHttpRequest();
const NEWS_URL :string = 'https://api.hnpwa.com/v0/news/1.json'
const CONTENT_URL :string = 'https://api.hnpwa.com/v0/item/@id.json';
const store :Store = {
...
}
function getData(url){
...
}
function makeFeeds(feeds){
...
}
function updateView(html){
...
}
function newsFeed(){
let newsFeed: NewsFeed[] = store.feeds;
...
}
function newsDetail(){
...
function makeComment(comments, called = 0){
...
}
}
function router(){
...
}
window.addEventListener('hashchange', router);
router();
먼저 제일 상단에 있는 const에서 선언한 변수들의 타입을 지정했다. dom요소에도 타입을 지정할 수 있는데 dom요소는 대부분 Element 타입과 null 타입이 공존하기 때문에 null 체크를 통한 타입가드를 해주어야한다. updateView() 함수가 id가 root인 dom요소의 타입가드를 해주는 로직의 함수이다. 또 ajax는 XMLHttpRequest 타입을 지정했다.
store객체의 currentPage(number), feeds(Array)의 타입을 지정하기 위하여 Store라는 타입을 새로 만들었는데 Store타입 안의 feeds 배열의 타입 또한 지정 해줄 수 있다. feeds 배열의 타입은 getData() 함수를 통해 API의 규격에 맞게 가져온 객체의 형식을 NewsFeed라는 타입으로 지정했다.
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #김민태의프론트엔드아카데미:제1강JavaScript&TypeScriptEssential
'study' 카테고리의 다른 글
패스트캠퍼스 챌린지 18일차 (0) | 2022.02.10 |
---|---|
패스트캠퍼스 챌린지 17일차 (0) | 2022.02.09 |
패스트캠퍼스 챌린지 15일차 (0) | 2022.02.07 |
패스트캠퍼스 챌린지 14일차 (0) | 2022.02.06 |
패스트캠퍼스 챌린지 13일차 (0) | 2022.02.05 |