TIL_230117_ Typescript 강의

정윤숙·2023년 1월 17일
0

TIL

목록 보기
78/192
post-thumbnail

내일배움캠프 4기 스파르타코딩 React B반


📒 오늘의 공부

1. Typescript 내배캠 강의

interface & Intersection Type

알게 된 것

  • interface

    • type이랑 비슷한 듯 한데 interface와 달리 type은 '='으로 정의
    • 선택 속성을 이용해 interface에는 있는 키를 선택적으로 넣지 않고 변수를 선언할 수 있다.
    • 필수 속성없이 모두 선택 속성으로 할 순 없다.
    • type, interface 모두 선택속성을 쓸 수 있다.
    • Read only 속성을 통해 내용을 불변으로 유지 가능
  • index type

    • 특정 프로퍼티를 미리 정하지 않을 수 있다.
  • interface 확장

    • 계속 이어서 확장시킬 수 있다.
// interface 확장
interface Person {
  name: string;
  age: number;
}

interface Korean extends Person {
  birth: "KOR";
}

interface Korean {
  name: string;
  age: number;
  birth: "KOR";
}

interface Developer {
  job: "developer";
}

interface KorAndDev extends Korean, Developer {}

interface KorAndDev {
  name: string;
  age: number;
  birth: "KOR";
  job: "developer";
}

const newPerson: KorAndDev = {
  name: "j",
  age: 33,
  birth: "KOR",
  job: "developer",
};
  • intersection Type

    • 여러 타입을 모두 만족하는 하나의 타입
      type DevJob = Person & Developer;
    • 공통요소가 들어 있는 두 개의 interface(Person,Developer)를 모두 만족
  • typeAlias와 interface의 차이

    • type은 바로 선언 가능 interface는 객체 형태
    • interface만 확장 가능
    • 가능한 interface로 선언해서 사용하기

⭐ interface, type은 전역으로 영향을 준다

  • typescript 설정을 따로 하지 않는 한 이 둘은 파일이 달라도 전역으로 영향을 준다.
  • 왼쪽의 nbcPerson에는 오른쪽 Developer에 있는 job이 빠져 있다는 오류
  • 오른쪽의 newPerson에는 왼쪽 Developer의 skill이 빠져있다는 오류가 뜬다.

⭐interface나 type을 쓸 땐 이름을 다르게 하기

제네릭

알게 된 것

  • 타입을 함수의 파라미터처럼 사용
    • 함수 실행 시 type(<string>등)은 생략 가능

타입 추론

알게 된 것

  • 타입을 생략해도 초기값에 따라 타입이 자동으로 선언된다.
    • 초기값이 없다면 type 기재

알게 된 것

  • splice()
  • 배열의 요소를 삭제, 추가할 때
  • splice(삭제를 시작할 index, 삭제할 개수, 추가할 내용)
  • 삭제할 개수를 정하기 않으면 시작부터 이후에 모든 요소를 제거

2. TypeScript로 todo list 만들기

React+Typescript Todolist

  • 빈 폴더의 터미널에서 실행
    npx create-react-app my-app --template typescript
    • 자동으로 tsx파일로 변환시켜줌
  • ✅ typescript 사용한 부분 다시 이해해보기

  • 초기 setup
    • 기존 프로젝트에서 쓸 때
    • npm install typescript @types/node @types/react @types/react-dom @types/jest @types/react-router-dom 한 번에 설치
    • js파일 -> ts
    • jsx파일 -> tsx
profile
프론트엔드 개발자

0개의 댓글