TypeScript와 클래스

김민석·2025년 8월 22일
post-thumbnail

클래스


Class Student {
	name,
    age

  // 생성자
  constrcut(name,age) {
  	this.name = name;
    this.age = age;
  }
  
  introduce () {
  	console.log(`안녕하세요 ${this.name} 입니다.`);
  }
}

let StudentB = new Student("김민석",27)

클래스는 비슷한 구조를 갖지만 상태는 다른 서로 다른 많은 객체를 만들 수 있다. new 를 이용해 새로운 인스턴스를 쉽게 만들 수 있다.

상속

extends 를 이용해 같은 프로퍼티와 메서드가 있는 것을 상속 받아 사용이 가능함. 상속받은 클래스에서 생성자에 super라는 함수를 호출해 부모 클래스에 생성자가 호출 됨 상속을 받은 프로퍼티만
super(name,age) 이런식으로 넣어줌

타입스크립트에서 클래스

const employee = {
	name:"김민석",
  	age:27,
  	position:"developer",
  	work() {
      console.log("일하는중")
    },
};

class Employee () {
	name: string;
  	age: number;
  	position: string;
	
  construtor(name: string,age: number,position: string,) {
  	this.name=name;
    this.age= age;
    this.position=position;
  }
  
   work() {
      console.log("일하는중")
    },
}
const employee2 = new Employee("김민석",27,"developer")

타입스크립트의 클래스는 타입으로도 사용이 가능함.
위의 Employee 는 타입으로도 사용이 가능함.

접근 제어자

public, private,protected가 있음. class에 아무것도 안쓰면 public이 기본값이다.

class Employee () {
	public name: string;
  	private age: number;
  	protected position: string;
	
  construtor(name: string,age: number,position: string,) {
  	this.name=name;
    this.age= age;
    this.position=position;
  }
  
   work() {
      console.log("일하는중")
    },
}
const employee2 = new Employee("김민석",27,"developer")

private로 필드를 설정하면 해당 클래스 밖에서 해당 프로퍼티를 접근하면 오류가난다. 파생 클래스에서도 메서드에서 접근이 불가능하다. 그냥 해당 나 자신의 클래스 에서만 접근이 가능함. 이럴때는 protected를 사용하면 파생 클래스 메서드에서 접근이 가능하다.

profile
나만의 기록장

0개의 댓글