TypeScript에서 Class, Interface 사용하기

Boo Sung Jun·2022년 3월 20일
0

TypeScript

목록 보기
7/8
post-thumbnail

1. Class

타입스크립트에서 클래스를 사용할 때는 아래와 같이 타입을 지정해준다.

  class Person {
    name: string; // name 필드 값 미리 지정해줘야 constructor에서 선언 가능

    // 리턴은 항상 오브젝트이기 때문에 리턴 타입은 굳이 명시 안해도 됨
    constructor(name: string) {
      this.name = name;
    }

    data = 0;

    함수(x: string): void {
      console.log(x);
    }
  }

  let 사람1 = new Person("kim");
  let 사람2 = new Person("park");

  사람1.함수("hello");



public

  • public은 클래스 내의 변수, 함수를 자식들이 이용 가능하게 한다. 그런데 public은 기본으로 적용되어 있어서 굳이 적지 않아도 된다.
  class 클래스 {
    // public 변수
    public name;
    age;  // public은 명시하지 않아도 기본으로 설정돼있 음.

    constructor(a) {
      this.name = this.name;
    }
    
    // public 함수
    public 함수() {
    }
  }

  // 자식들은 public 변수 사용 가능
  let 자식 = new 클래스("park");
  자식.name = "hi";
  • public 키워드를 사용하여 선언과 'this.변수'를 생략할 수 있다.
  class Person {
    // 바로 name 변수에 할당
    constructor(public name: string) {}
  }

  let 사람 = new Person("john");
  console.log(사람.name);  // 출력: john



private

private은 클래스 내에서만 사용이 가능하게 한다. 따라서 자식에서 수정이 불가능하다. 만약 클래스 외부에서 private 속성을 변경하려면 setter 함수를 만들어서 사용해야 한다.

  class 클래스 {
    // 클래스 내에서만 수정 가능
    private name = "kim";

    constructor() {
    }

    // 외부에서 private 속성 변경하려면 함수 만들어서 쓰기
    이름변경함수(a: string) {
      this.name = a;
    }
  }



protected

protected는 속성을 extends된 클래스에서 사용 가능하게 한다.

  class User {
    protected x = 10;
  }
  
  class NewUser extends User {
    
    doThis(){
      console.log(this.x);
    }
  }

  let x = new NewUser().doThis();  // 출력: 10



static

  • static은 클래스 내에서만 사용 가능하고 자식은 사용할 수 없게 한다.
  class 클래스 {
    static x = 10;
  }

  let 자식 = new 클래스();
  console.log(자식.x);  // 에러: x가 존재하지 않음
  console.log(클래스.x);
  • static은 extends해도 같이 따라온다.
  • static은 public, private와 같이 사용할 수 있다.
  • static 변수는 this.변수로 사용하지 않고 클래스명.변수로 사용한다.
  class 클래스 {
    // static은 public, private와 같이 사용 가능
    public static x = 10;

    // static 변수는 this.변수로 사용하지 않고 클래스명.변수로 사용
    y = 클래스.x + 10;
  }

  let 변수 = new 클래스();
  console.log(변수);  // 출력: 클래스 { y: 20 }
  클래스.x = 30;
  console.log(변수);  // 출력: 클래스 { y: 20 }
  let 변수2 = new 클래스();
  console.log(변수2);  // 출력: { y: 40 }

2. Interface

  • Object에 타입 지정할 때, type alias를 사용하지 않고, interface를 이용할 수 있다.
 interface Square {
    color: string;
    width: number;
  }

let 네모: Square = { color: "red", width: 100 };

위 예시의 인터페이스는 아래 type alias와 같은 기능을 한다.

type Square = { color: string; width: number };
  • extends를 사용하여 부모 인터페이스의 속성들을 상속 받을 수 있다.
  interface Student {
    name: String;
  }

  interface Teacher extends Student {
    age: number;
  }

  let 학생: Student = { name: "kim" };
  let 선생: Teacher = { name: "park", age: 20 };
  • 인터페이스 내의 속성으로 함수를 넣을 수도 있는데, 이 경우에는 다음과 같이 타입 지정이 가능하다
// object 에 함수 저장할 수 있음
  interface Operator {
      plus: (a: number, b: number) => number;
      minus: (a: number, b: number) => number;
    }

  let obj: Operator = {
    plus(a, b) {
      return a + b;
    },
    minus(a, b) {
      return a - b;
    },
  };



Interface vs Type Alias

type alias에서도 interface의 extends와 비슷한 기능이 있다. intersection type을 이용하는 것이다.

 // intersection type 이용
  type Animal = { name: string };
  type Cat = { age: number } & Animal;

그러나, interface는 중복 선언 가능하지만, intersection은 불가능하다.

  interface Student {
    name: String;
  }

  interface Student { score: number };

위 코드에서 Student에 score 속성이 추가된다.

그리고 interface, type alias 둘 다 기존 속성 변경 불가능하다.

  interface Student {
    name: String;
  }
  interface Student { name: number };  // 에러

  type Dog = { name: number } & Animal;
  let: Dog = {name: 123}  // 에러(never 타입)

보통 interface가 더 자주 사용된다.

0개의 댓글