TypeScript 클래스 학습하기

AN JUHYUN·2024년 2월 19일

react-native 개발일지

목록 보기
5/15

ES6의 클래스를 다룬다는 가정으로 자바스크립트와 차이점을 공부하자!!

class 선언

// 클래스 만들기
class Car{
	constructor(color){
    	this.color = color;
    }
    start(){
    	console.log('start');
    }
}
// 인스턴스 생성
const bmw = new Car('red');

위의 코드는 javascript에서 에러가 없지만 typescript에서 에러가 발생함
왜??

typescript에서 class 작성할 때 멤버변수는 미리 선언해주어야한다.
미리 선언하지 않으려면 접근제한자(public 등)또는 readonly를 적어주면 된다.

// 클래스 만들기
class Car{
	// 멤버변수 선언
	color: string;
    // 파라미터 타입 맞추기(any를 string로)
	constructor(color:string){
    	this.color = color;
    }
    start(){
    	console.log('start');
    }
}

접근제한자(Access modifier) - public, private, protected

public

자식클래스나 클래스인스턴스에서 접근 가능.
안적으면 기본값으로 public임.

private

자식클래스 내부에서 사용할 수 없음.
해당 클래스에서만 접근 가능.
private 또는 #으로 작성해서 표현할 수 있음.

protected

자식클래스에서 접근 가능함.
public과 달리 클래스 인스턴스에서는 접근할 수 없음.

readonly 읽기전용

class Car{
	readonly name: string = 'car';
    constructor(name){
    	this.name = name;
    }
}

class Bmw extends Car{
	constructor(name){
    	super(name);
    }
}

// readonly의 경우 
const b4 = new Bmw('b4');

읽기전용을 설정한 경우 값을 고치기 위해서 생성자에 값을 받아서 처리가능하다.

static

class Car{
	static wheels = 4;
	readonly name: string = 'car';
    constructor(name){
    	this.name = name;
    }
}
console.log(Car.wheels);

static으로 선언 된 정적멤버변수를 클래스명으로 접근할 수 있다.

추상 class

이름이나 메서드의 이름만 선언해주고 구체적인 기능은 상속받는 쪽에서 구현하는 클래스

abstract class Car{
	readonly name: string = 'car';
    constructor(name){
    	this.name = name;
    }
    abstract doSomething():void;
}

class Bmw extends Car{
	constructor(name){
    	super(name);
    }
    doSomething(){
    	alert(3);
    }
}

// new키워드로 객체생성이 불가하다
// const b4 = new Bmw('b4'); 

차이점?

현재는 자바스크립트도 class 와 접근제한자등 거의 비슷하게 적용 가능하다.
그래도 배워두면 쓸모있지!

profile
frontend developer

0개의 댓글