[Typescript] 공부하기

Swimme·2021년 1월 9일
0

Typescript

목록 보기
1/2

TIL 2021. 01. 06

Typescript

  • JS의 super-set: Javascript에 타입이 추가된 것
  • 정적 타입을 지원: 타입 명시
    • 그외 Type inference, 좀 더 객체 지향적 기능 (interface 등) 제공

1. Types

  • primitive) boolean, number, string, void, null, undefined
  • any, never (Error - 리턴값 발생하지 않는 경우)
  • tuple: 고정된 개수와 타입 명시
    const getExample = (): [ number, string ] => {
        return [Math.random(), "example" ];
    }
    enum Color {
        red,
        blue,
        green = "green"
    }
    //{ '0': 'red', '1': 'blue', red: 0, blue: 1, green: 'green' }
    // 값 할당하지 않으면 자동으로 0부터 숫자매김
    // 리버스 매핑도 지원

    let greenColor: Color = Color.green;

  • Type Inference
    • 함수 호출시 return값을 타입 명시하지 않아도 inference됨
    • 타입에 종속되는 메소드도 자동 추천됨

  • Type Assertion
    • 리턴 타입이 여러 개인 경우
    • 호출 시 리턴 타입 명시 (컴파일할 때)
    • 실제로 권장하지 않는 경우 but 제작된 라이브러리 사용시 쓰는 경우 있음
    • Type casting 과는 다름 (= 런타임때 보장)
      const validateAge = (age: number)=> {
          if (age < 100) {
              return `${age}`.
          }
          return false;
      }

      //Type Assertion
      const myAge = validateAge(23) as number;

      //Type Casting
      const myAge = String(23)

2. Class

    class Person {
      constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
      }

      public name: string;
      private age: number;

      greet() {
        return `Hello, I am ${this.name}. I'm ${this.age}.`;
      }
    }

    const soo = new Person("Soo", 23);
    console.log(soo.greet());
    console.log(soo.name);
// soo.age;
  • abstract class

3. Interface

  • 어떤 값이 어떻게 존재해야 하는 지를 명시 ( ex. 함수의 입출력 타입 )
    • 함수의 인자가 3개 이상인 경우엔 interface를 이용하여 입력값을 명시 하는 것이 바람직
  • 컴파일 시에만 존재
  • 인터페이스를 상속하여 구현한 클래스
    interface Animal {
        eat (something: string): void;
        hobby? : string; //* Optional property
    }
    //Animal이란 객체가 eat메소드 가져야함을 명시

    class Person implements Animal {
        private readonly name: string;

        public constructor(name: string) {
            this.name = name;
        }

        public eat(something: string) {
        console.log(`${this.name} eats ${something}`);
      }
    }

설치 및 실행

  1. 프로젝트 초기화
  npm init -y
  1. typescript 설치
  npm i -D typescript
  // package.json에 이렇게 뜸
  "devDependencies": {
      "typescript": "^4.1.3"
  }
  1. typescript 컴파일
  npx tsc sample.ts
  • 참고

    • devDependencies : 개발할 때만 필요한 패키지 (실행할 때 필요한 것 x)

      • 실행은 원래 js로 컴파일 후 되는 실행되므로 dev option을 준 것
    • npx: Package runner

      • 현재 프로젝트에서 설치된 프로그램 실행
      • 설치되지 않은 경우 일회성으로 설치 후 실행 (이후 제거)
      • cf. npm은 Package manager (설치 및 관리)
      • npm으로 global 설치한 경우 npx필요 없음
    • tsc: typescript compiler




공식 홈페이지: https://www.typescriptlang.org/docs/handbook/basic-types.html

번역 홈페이지: https://typescript-kr.github.io/pages/basic-types.html

Nest.js를 사용할때 살짝 써보고 제대로 공부하는 것은 처음이다. 공식문서와 프론트엔드를 공부하며 React와 사용해볼 계획이다. 겨울방학이 끝나기 전에 JS와 Express로 했던 백엔드 공부에도 적용해봐야겠음.

profile
Life is Egg..🥚🐣🌟

0개의 댓글