Typescript #3 - class

Fstone·2020년 12월 8일

Typescript

목록 보기
3/3
post-thumbnail

Class

  • typescript에서 속성과 method의 type을 정의하고 instance로 상속하기 위해 interfaceclass를 사용할 수 있다. 하지만 typescript는 js로 compile되고 js에서 interface는 존재하지 않아 interface는 js로 compile되지 않는다.

따라서 상황에 따라 interfaceclass를 적절하게 사용할 수 있어야 한다.

Class 속성 정의

class User {
  public id: number;
  public name: string;
  public email: string;
  
  constructor(id: number, name: string, email: string) {
    this.id = id;
    this.name = name;
    this.email = email;
  }
}

const newer = new User(1, "fstwon", "velog.io/@fstone")
// User { id: 1, name: 'fstwon', email: 'velog.io/@fstone' }
  • class 접근 제한자: 부모 class와 자식 class와 자식 class의 instance에서 속성과 method 접근 가능 여부를 정의한다.

    • public: 부모, 자식 class와 자식 class의 instance에서 모두 속성과 method를 사용할 수 있다.

    • private: 속성과 method가 정의 된 class에서만 접근이 가능하다.

    • protected: 부모, 자식 class에서 속성과 method를 사용할 수 있지만 자식 class의 instance에서는 접근할 수 없다.

    • readonly: 자식 class에서 속성은 읽기만 가능하고 변경할 수 없다.

  • 정적 method, static
    class를 상속하기 전에 class를 통해 사용되어야 하는 method를 선언할 때는 method 앞에 static keyword를 사용한다.

class User {
  public id: number;
  public name: string;
  public email: string;

  constructor(id: number, name: string, email: string) {
    this.id = id;
    this.name = name;
    this.email = email;
  }

  static userValid(): void {
    console.log("this is a static Method");
  }
}

class newUser extends User {
  constructor(id, name, email) {
    super(id, name, email);
  }
}

const user = new newUser(1, "fstwon", "velog.io/@fstwon");

console.log(User.userValid());
// this is a static Method
console.log(newUser.userValid());
// this is a static Method
console.log(user.userValid());
// Property 'userValid' is a static member of type 'newUser'

static keyword로 선언된 method는 class 상속으로 자식 class에서도 사용할 수 있지만 instance로는 상속이 안되어 사용할 수 없다.

Abstract Class

  • interface와 비슷한 개념으로 이름과 type만 정의한 추상 method일반 method를 추가할 수 있다.

  • 추상 class는 직접 instance를 생성할 수 없고 상속만 가능하다.

  • 추상 method는 상속받은 class에서 반드시 구현되어야 한다.


abstract class User {
  public id: number;
  public name: string;
  public email: string;

  constructor(id: number, name: string, email: string) {
    this.id = id;
    this.name = name;
    this.email = email;
  }

  abstract method(name: string): void;

  userValid(): boolean {
    if (this.name && this.email) {
      return true;
    } else {
      return false;
    }
  }
}

class newUser extends User {
  constructor(id, name, email) {
    super(id, name, email);
  }

  method() {
    console.log(this.name);
  }
}

const user = new newUser(1, "fstwon", "velog.io/@fstwon");

console.log(user.method());
// fstwon
console.log(user.userValid());
// true

Reference

https://www.typescriptlang.org/docs/handbook/intro.html

https://poiemaweb.com/typescript-class

0개의 댓글