이번 EP에서는 기존의 JS코드를 TS코드로 변환하는 과정이다.
TS는 타입스크립트라 부르며 JS와 달리 정적 타입 언어의 컴파일 언어이다. 코드 작성 중에 타입을 체크하여 오류를 빠르게 확인하여 수정할 수 있어 실행 속도가 매우 빠르다. 하지만 코드 작성 중에 타입을 일일이 지정해야하기 때문에 컴파일 시간이 JS보다 길다는 단점이 있다.
const container: HTMLElement | null = document.getElementById("root");
const ajax: XMLHttpRequest = new XMLHttpRequest();
const content: HTMLDivElement = document.createElement("div");
const store: Store = {
currentPage: 1,
feeds: [], //글 읽음 표시 유무를 위한 배열
};
기존 코드에서 많은 변화는 없다. 명시된 변수 뒤에 :을 붙이고 타입을 지정해주면 TS의 첫걸음을 내딛는 것이다.
function makeFeeds(feeds: NewsFeed[]): NewsFeed[] {
for (let i = 0; i < feeds.length; i++) {
feeds[i].read = false;
}
return feeds;
}
변수를 지정할 때, 타입을 지정할 수 있으며 함수의 파라미터 값에도 :을 붙여 타입을 지정한다.
입력 값의 타입과 반환 값의 타입을 지정할 수 있다.
type News = {
id: number;
time_ago: string;
title: string;
url: string;
user: string;
content: string;
}
타입 알리아스는 새로운 타입을 지정한다.
type NewsFeed = News & { // intersection 기능 (중복 생략 가능)
comments_count: number;
points: number;
read?: boolean; // ?는 선택 속성을 의미
}
타입 알리아스에서 &를 넣어 중복되는 값들을 줄일 수 있다.
interface News { //interface와 type alias의 차이는 '='의 유무이다.
id: number;
time_ago: string;
title: string;
url: string;
user: string;
content: string;
}
가장 큰 차이점은 타입을 결합시키거나 조합시키는 방식의 차이이다.
interface NewsFeed extends News {
comments_count: number;
points: number;
read?: boolean;
}
type alias의 '&'와 달리 interface에서는 확장한다는 의미인 'extends'를 사용한다.
News를 통해 NewsFeed, NewsComment와 같이 확장되는 형식의 타입들은 인터페이스를 선호한다.
interface News {
readonly id: number; // readonly: 변경 불가 기능
readonly time_ago: string;
readonly title: string;
readonly url: string;
readonly user: string;
readonly content: string;
}
readonly : 변수가 변경되지 않도록 지정해주는 기능