[TS] 타입 단언과 모듈

단비·2023년 3월 8일
0

인강

목록 보기
7/15
  • js 파일을 생성하지 않고 컴파일 하는 방법
    1. npm install -g -ts-node 설치
    2. ts-node 파일명.ts 명령어로 ts 파일 실행
  • npm install -D @types/node
    • node의 타입을 전부 삽입해주는 패키지

  • 타입 단언
    1. document에서 아이디값에 해당하는 엘리먼트를 가져오려할 때 오류가 발생

      (이유는 null 일수도 있기 때문)

      • 해결방법
        1. 값을 사용할 때 물음표를 사용

          testText?.id

        2. 값을 찾을 때 느낌표를 사용

          document.querySelector("#someText")!

        3. as를 이용한 타입 선언

          document.querySelector("#someText") as HTMLElement

    2. object 타입으로 선언한 변수의 키값 선택의 오류

      const example: object = { value: 1 }
      console.log(example.value) // 오류 발생

      • 해결방법
        1. 인터페이스를 이용한 as 활용

          interface IExam { value: number }
          console.log((example as IExam).value)
        2. 인터페이스를 이용한 제네릭 활용

          interface IExam { value: number }
          console.log((<IExam>example).value)

  • any와 unknown의 차이점
    • any
      • 어떠한 타입도 허용하는 타입
      • 타입에 맞지 않는 값을 불러오려해도 컴파일 시 에러가 나지 않고 출력 시 undefined으로 출력됨
    • unknown
      • 모든 값을 허용하지만, 할당된 값이 어떤 타입인지 모르기 때문에 함부로 프로퍼티나 연산을 할 수 없음

  • typeof
    • 해당 값의 타입을 반환

    • 아래와 같이 사용 가능

      const exString: string = "some string"
      const childString: typeof exString = "haha"

  • 조건부 타입
    • 아래와 같이 활용 가능
      - ISchool이 ICity를 상속받는 것이 참이기 때문에 number 타입으로 설정됨

      interface ICity {
          name: string
      }
      
      interface ISchool extends ICity{
          year: number
      }
      
      type ConditionType = ISchool extends ICity ? number : string;
      const text: ConditionType = 123

  • 모듈
    • import 방법
      1. 불러올 함수 직접 선언

        import { add, minus } from "./module1"
        console.log(add(1, 2), minus(3, 1))
      2. 해당 파일의 전체 함수를 불러와 별명 짓기

        import * as MATH from "./module1"
        console.log(MATH.add(1, 2), MATH.minus(3, 1))
    • namespace
      • 네임스페이스를 이용한 모듈 선언 시 다른 패키지의 함수와 헷갈리지 않아 오류가 발생하지 않음

        export namespace DANBIMATH {
            export function add(a: number, b: number){
                return a + b
            }
        
        // 사용시
        import * as M from "./module1"
        console.log(M.DANBIMATH.add(1, 2))
profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글