JavaScript/TypeScript

[TypeScript] 클래스와 접근 제어자

J-Plum 2023. 4. 10. 02:59

클레스

클레스에서 위에 타입을 지정해주지 않으면 에러가 발생합니다.

 

js에서는 문제가 없는 코드이지만

 

Ts에서는 constructor 가 지정되기 전에 미리 타입이 지정되어 있어야합니다.

 


접근 제어자

public : 자유롭게 접근 가능, 클래스내 생략 가능

protected : 자신과 파생된 후손 클래스 내에서 접근 가능

private : 클래스 내에서만 접근 가능

 


추가내용

클래스 위에서 타입을 지정하지 않고 생성자에서 접근제어자와 함깨 작성한다면 생략 가능합니다.

(단! 이때 public은 생략할 수 없습니다.)

 

소스코드

class User1 {
  constructor(
    public first: string,
    public pet: string,
    public age: number
  ) {
    this.first = first;
    this.pet = pet;
    this.age = age;
  }
  getAge() {
    return `${this.first} ${this.pet} is ${this.age}`;
  }
}

class User2 extends User1 {
  getAge() {
    return `${this.first} ${this.pet} is ${this.age}`;
  }
}

class User3 extends User2 {
  getAge() {
    return `${this.first} ${this.pet} is ${this.age}`;
  }
}

const Jplum = new User1("J-plum", "Euang", 4236798);
console.log(Jplum.first);
console.log(Jplum.pet);
console.log(Jplum.age);