TypeScript

  1. 왜 타입스크랩트를 써야하나.
  2. TypeScipt 기초
  3. 함수 타입을 정의하자
  4. interface를 활용하자
  5. 타입 별칭이란?
  6. 연산자를 이용한 타입 정의 - 유니온 타입
  7. enum
  8. class
  9. generic
  10. promise Types
  11. todolist 만들어보기
  12. 디버깅

목차

제네릭을 왜 써야할까?

코드의 재사용성을 높이자

function consoleLogText(text) {
  text.split("");
  return text;
}
consoleLogText("string");
consoleLogText(123);

function consoleLogNumber(text) {
  return text;
}

consoleLogNumber(123);
function consoleLogTypeString(text: string | number) {
  if (typeof text === "string") {
    text.split("");
  }
  if (typeof text === "number") {
    text.toString();
  }
  return text;
}

const stringType = consoleLogTypeString("string");
stringType.split(""); // 에러 발생
const numberType = consoleLogTypeString(123);
stringType.toLocaleString();
'string | number' 형식에 'split' 속성이 없습니다.
'number' 형식에 'split' 속성이 없습니다.ts(2339)

이런 문제를 해결하기 위해서 제네릭 타입을 사용한다

function genericType<T>(text: T): T {
  return text;
}
const stringGeneric = genericType<string>("string");
stringGeneric.split("");
const numberGeneric = genericType<number>(123);
numberGeneric.toString();

인터페이스를 적용해보자

인터페이스 예제

interface Dropdown<T> {
  value: T;
  selected: boolean;
}
const objectStringConst: Dropdown<string> = {
  value: "string",
  selected: true,
};

const objectNumberConst: Dropdown<number> = {
  value: 123,
  selected: true,
};