ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 타입스크립트(2) - ES6, 클래스 함수(1)
    웹 개발/typescript 2023. 5. 31. 14:46

    타입스크립트와 ES6 

    - 타입스크립트는 쉽게 생각해서 자바스크립트의 확장판이기 때문에 자바스크립트에서 사용하던 문법을 그대로 사용 + 새로운 타입스크립트만의 문법 이렇게 생각하면 됨 

    - 타입스크립트 ES6 = 자바스크립트 ES6

     

    블록 스코프 

    context.ts

    let context = document.querySelector('html');
    
    {
      let context = document.querySelector('body');
      console.log('블록문 내부 context = ', context);
    }
    
    console.log('글로벌 context = ', context);

     

    템플릿 리터럴

    - 템플릿(문자열)을 접합하는 것을 의미함 

    - 데이터를 가져와서 넣어서 출력하는 것을 의미함 

    - ${변수이름} 

    let nickname = 'yamoo9';
    
    let greeting_message = `
      <p>
        안녕하세요 <strong>${nickname}</strong>님.
        가입을 환영합니다. :-)
      </p>
    `;

     

    화살표 함수 

    - 매개변수, 리턴 타입을 명시적으로 선언해 컴파일 과정에서 타입 검사를 수행하여 사전 문제를 방지할 수 있음 

    let corsURL = (url:string): string => `https://crossorigin.me/${url}`;
    
    corsURL('http://yamoo9.herokuapp.com/rest/ediya-menu');

     

    자바스크립트 형태로 작성하면,

    let corsURL = function (url) {
      return "https://crossorigin.me/" + url;
    };
    
    corsURL('http://yamoo9.herokuapp.com/rest/ediya-menu');

    - 매개변수 url은 string 타입이라고 명시해줌 : = (매개변수 : 매개변수 타입) => 

     

    - return 형태 만들기 

         

    : 리턴 타입 => '템플릿/${붙여줄 매개변수}'

     

    따라서, 종합해보면 이런 형태로 화살표 함수를 만들 수 있다. 

    const 변수 이름 = (매개변수이름 : 매개변수 타입) : 리턴타입 => '반환할 항목';

     

     

    연산자와 매개변수 

    Default Parameter(기본 매개변수)

    - 매개변수 타입 설정 후 '=' 이후 기본 값을 할당한다. 

     

    coutDown.ts

    function countDown(start:number = 10): ()=>number {
      return () => start > 0 ? start-- : 0;
    }

     

    countDown.js

    function countDown(start) {
      if (start === void 0) { start = 10; }
      return function () { return start > 0 ? start-- : 0; };
    }

     

    - countDown 함수는 start라는 매개변수를 가지며, 이 매개변수의 기본값은 10이고, number type을 가진다. 

    - 다음 return에는 함수가 반환되는데, 

    number {
      return () => start > 0 ? start-- : 0;
    }

    - 이때, 익명함수(function () => {. . .})가 반환된다.

    - start 값이 0보다 큰 경우( ? ) start 값을 감소시키고 반환된다. 그렇지 않은 경우, 즉 start 값이 0인 경우 0을 반환된다.

     

    Spread Operator

    // 배열 선언
    let numbers:number[] = [101, 21, -12, 934, 87];
    
    // 배열 내부 아이템으로 결합
    numbers = [10, 31, 11, ...numbers, -2, 0];
    // [10, 31, 11, 101, 21, -12, 934, 87, -2, 0]이 된다.
    
    
    // 배열 ⟹ 개별 아이템으로 순차적 제공
    let min_number:number = Math.min(...numbers);
    let max_number:number = Math.max(...numbers);

     

    - 배열을 배열 내부 아이템으로 결합하기 

    ,...배열변수 이름,

     

    나머지 매개변수(Rest Parameters)

    - 전개 연산자를 매개변수 앞에 붙여 사용함

    - 함수에서 활용된다. 

    - 가변인자 즉 매개인자를 배열타입으로 할당하여 사용할 때 작성한다. 

    - args... : args의 타입 

    function makeArray(...args:(number|string)[]): (number|string)[] {
      return args;
    }
    
    makeArray(11, 'eleven', 100, 'one hundred');

    - makeArray 함수는 ...args라는 가변 인자를 받는다. 이 때 ' : '을 통하여 배열의 원소 타입이 선언되는데, 이 가변 인자는 (number|string)[] 형태로 선언되어 있으며, 숫자 또는 문자열로 이루어진 배열 타입이다.

    - return args이기 때문에 args 가변인자 자체를 그냥 리턴값으로 반환된다. 

     

     

    비구조화 할당 

    - 배열, 객체의 아이템 또는 속성을 변수에 할당할 때 사용한다. 

    // 배열 비구조화 할당
    let [html, , body] = [document.documentElement, document.head, document.body];
    
    // 객체 비구조화 할당
    let numbers_module = {
        multiplyNumbers: (...n:number[]):number => n.reduce((a, b) => a * b),
        sumNumbers: (...n:number[]):number => n.reduce((a, b) => a + b)
    };
    
    let { sumNumbers } = numbers_module;

     

     

    클래스(1) 

     

    접근 제어자 

    - 접근 제어자(access modifiers)를 통해 접근 가능한 범위를 설정할 수 있고, 각 속성에 데이터 타입을 지정할 수 있게 하는 typescript의 고유한 문법

     

    1. 접근 제어 속성

    class Book {
    
      // 제목
      // public: 클래스 외부에서 접근 가능
      public title:string;
    
      // 저자
      // public은 기본 값으로 생략 가능합니다.
      public author:string;
    
      // 제조 공장 : _manufacturing_plant
      // private: Book 클래스 내부에서만 접근 가능
      private _manufacturing_plant:string;
    
      // 종이 유형 papter_type
      // protected: Book 클래스를 포함한 서브 클래스에서만 접근 가능
      protected paper_type:string;
    
      // constructor() 매개변수 앞에 
      // public, private, protected를 사용하면
      // Book 클래스의 타입(type)을 별도 선언하지 않아도 됩니다. constructor은 초기화임. 즉 사용변수를 선언해주는 것을 의미함
      constructor(title:string, author:string, public pages:number) {
        this.title = title;
        this.author = author;
        this.pages = pages;
      }
    
    }
    
    /* 인스턴스 생성 ------------------------------------------------ */
    
    let indRevo = new Book('한 권으로 정리하는 4차 산업혁명', '최진기', 367);
    console.log(indRevo); // Book {}

     

    1. 변수의 속성을 설정해준다. 

     

    public title : string;
    public author : string;
    private _manufactoring_plant : string;
    protected paper_types : string;

     

    2. 클래스 변수 안에서 인스턴스 변수를 선언한다.(constructor) 즉, 외부에서 받아올 사용 변수를 선언함

      constructor(title:string, author:string, public pages:number) {
        this.title = title;
        this.author = author;
        this.pages = pages;

     

     

     

     

    2. 접근 제어 메서드 

    - 메서드는 변수가 아니기 때문에, (변수로서 사용할 수 있지만) constructor을 사용하지 않는다. 

    class Book {
    
      public    title:string;
      public    author:string;
      public    pages:number = 150;
      private   _manufacturing_plant:string = '충무로 공장';
      protected paper_type:string = '밍크지';
    
      constructor(title:string, author:string, pages:number) {
        this.title  = title;
        this.author = author;
        this.pages  = pages;
      }
    
      /* 메서드 ------------------------------------------------ */
    
      // public 메서드
      // 클래스 외부에서 접근 가능
      public printPages(): string {
        return `${this.pages}페이지`;
      }
    
      // protected 메서드
      // Book 클래스를 포함한 서브 클래스에서만 접근 가능
      protected changePaperType(type:string): void {
        this.paper_type = type;
      }
    
      // private 메서드
      // Book 클래스 내부에서만 접근 가능
      private setManufacturingPlant(plant:string): void {
        this._manufacturing_plant = plant;
      }
    
    
      /* 클래스 내부 메서드에서 private, protected 메서드 접근 가능 */
    
      public setPaperType(type:string):void {
        // protected 메서드 접근 가능
        this.changePaperType(type);
        console.log(this.paper_type);
      }
    
      public setPlant(plant:string):void {
        // private 메서드 접근 가능
        this.setManufacturingPlant(plant);
        console.log(this._manufacturing_plant);
      }
    
    }
    
    
    /* 인스턴스 생성 ------------------------------------------------ */
    
    let indRevo = new Book('한 권으로 정리하는 4차 산업혁명', '최진기', 367);
    
    console.log(indRevo.printPages()); // '367페이지'
    
    // [오류]
    // [ts] 'changePaperType' 속성은 보호된 속성이며
    // 'Book' 클래스 및 해당 하위 클래스 내에서만 액세스할 수 있습니다.
    // (method) Book.changePaperType(type: string): void
    console.log(indRevo.changePaperType('인디언지'));
    
    // [오류]
    // [ts] 'setManufacturingPlant' 속성은 private이며
    // 'Book' 클래스 내에서만 액세스할 수 있습니다.
    // (method) Book.setManufacturingPlant(plant: string): void
    console.log(indRevo.setManufacturingPlant('파주 공장'));

    '웹 개발 > typescript' 카테고리의 다른 글

    typescript(5) - 인터페이스  (0) 2023.06.25
    typescript(3) - 모듈 , 네임스페이스  (0) 2023.06.25
    Typescript(3) - 클래스 패턴  (0) 2023.06.04
    Typescript(1) - 설치와 시작  (0) 2023.05.24
Designed by Tistory.