JSTS

[TS] 실습 4. 엄격한 타입 적용

Jaaaay 2022. 7. 28. 16:08

strict 옵션

tsconfig.json compileOptions에 "strict": true 추가

TSConfig Reference - Docs on every TSConfig option

{
  "strictNullChecks": true,
  "strictFunctionTypes": true,
  "strictBindCallApply": true,
  "strictPropertyInitialization": true,
  "noImplicitThis": true,
  "alwaysStrict": true,
}

즉 strict를 설정하면 위와 같은 설정들이 true로 설정된다.


null 타입 오류 및 함수 타입 오류 해결

1.

'Event' 형식에 'MouseEvent' 형식의 altKey, button, buttons, clientX 외 21개 속성이 없습니다.

strict를 적용하면 Event 타입의 하위타입을 허용하지 않아 오류가 발생했다.

2.

null일 경우 처리를 별도로 해주어야 함.


타입 단언을 이용한 타입 에러 해결

querySelector를 통해 값이 할당된 deathsList는 Element | null 타입으로 추론된다.

null이 아닌 것을 확신할 수 있는 경우 non-null assertion을 !. 을 통해 할 수 있다.


옵셔널 체이닝 연산자

?. 을 통해 nullish한 경우 에러를 발생시키지 않고 undefined를 반환할 수 있다.

에러 핸들링의 역할도 수행한다.

아래 두 코드가 같은 동작을 함.

recoveredList?.appendChild(li);
if (recoverdList === null || recoveredList === undefined) {
	return;
} else {
	recoveredList.appendChild(li);
}

DOM 유틸 함수 활용성을 높이는 타입 정의

// utils
function $(selector: string) {
  return document.querySelector(selector);
}

// DOM
// let a: Element | HTMLElement | HTMLParagraphElement;
const confirmedTotal = $('.confirmed-total') as HTMLSpanElement;
const deathsTotal = $('.deaths') as HTMLParagraphElement;

위 코드를 가독성이 좋게 만들기 위해 제네릭을 이용해보자

// utils
function $<T extends HTMLElement>(selector: string) {
  const element = document.querySelector(selector);
  return element as T;
}

// DOM
// let a: Element | HTMLElement | HTMLParagraphElement;
const confirmedTotal = $<HTMLSpanElement>('.confirmed-total');
const deathsTotal = $<HTMLParagraphElement>('.deaths');

다음과 같이 만들 수 있다.

HTMLElement의 자식요소가 아닐경우 error가 난다.

function $<T extends HTMLElement = HTMLDivElement>(selector: string) {
  const element = document.querySelector(selector);
  return element as T;
}

다음과 같이 기본값을 따로 지정해줄 수도 있다.