JavaScript & TypeScript Essential - (type alias / typeguard)

김명성·2022년 4월 11일

타입스크립트는 트랜스파일러이기 때문에 자바스크립트로 변환하는 과정이 필요하다.

sourcemap : 실제 브라우저에서 작성했던 타입스크립트에서 문제점을 찾을 수 있게 source의 지도같은 개념.


ajax 변수의 XmLHttpRequest() 에 마우스 커서를 올려보면

const ajax = new XMLHttpRequest();
타입스크립트에서는 다음과 같이 표시된다.
var XMLHttpRequest: new () => XMLHttpRequest
new 생성자 함수를 실행함으로서 XMLHttpRequest라고 하는 타입이 반환된다는 뜻이다.

객체의 타입
객체는 프로퍼티마다 타입이 다를 수 있다.
type alias 와 interface를 사용할 수 있다.
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;
}

type alias : 중복의 제거

// API에서 받아오는 데이터 중 사용할 프로퍼티의 type 명시.
type News = {
  content: string;
  id: number;
  time_ago: string;
  title: string;
  user: string;
  url: string;
}
type NewsFeed = News & {
  comments_count: number;
  points: number;
  read?: boolean;
}

type NewsDetail = News & {
  comments: NewsComment[];
}

type NewsComment = News & {
  comments: NewsComment[];
  level:number;
}
type guard

function updateView(html){
  if(container != null){
    container.innerHTML = html;
    }else{
      console.error("최상위 컨테이너가 없어 UI를 진행하지 못합니다.")
    }
}

updateView(html)
updateView( template.replace('{{__comments__}}', makeComment(newsContent.comments)))
함수의 리턴값 정의
//getData는 NewsFeed[] | NewsDetail type을 반환한다
function getData(url: string): NewsFeed[] | NewsDetail {
  ajax.open('GET', url, false);
  ajax.send();
  //객체로 바꾼 뒤 리턴한다.
  return JSON.parse(ajax.response);
}

제네릭

함수의 리턴 값으로 유니온 타입을 기술하는 것만으로는 한계가 발생할 때 제네릭을 사용한다.

제네릭은 입력되는 값이 n개의 유형일 때, 출력도 n개의 유형이라고 정의하는 기술이다. 만약 입력이 string이라면, 출력도 string으로 나가고 입력이 특정 사용자 정의 타입이라면 , 출력도 특정 사용자 정의타입으로 받아야 한다.
제네릭의 사용
함수 명과 소괄호 사이에 <T> 와 소괄호 끝에 : T를 붙인다. 그리고 함수 호출부에서 응답 받기 원하는 타입을 지정한다.
// getData 함수를 호출하는 코드가 수십개이고
// 저마다 리턴해야 하는 타입이 다르다면 제네릭을 사용한다.
function getData<AjaxResponse>(url: string): AjaxResponse {
  ajax.open('GET', url, false);
  ajax.send();
  return JSON.parse(ajax.response);
}

//아래 함수 호출을 통해 얻는 값의 타입은 <NewsDetail> 타입이어야 한다.
 const newsContent = getData<NewsDetail>(CONTENT_URL.replace('@id', id));


if(newsFeed.length === 0){
   // 아래 함수 호출을 통해 얻는 값의 타입은 <NewsFeed[]> 타입이어야 한다. 
    newsFeed = store.feeds = makeFeeds(getData<NewsFeed[]>(NEWS_URL));
  }

0개의 댓글