급변하는 기술 시장에서 살아남기 위해 Typescript 공부를 시작하였습니다...
과연 저는 살아남을 수 있을까요?!
타입스크립트에서는 클래스를 어떻게 쓰면 될까요?
프로퍼티의 타입 지정, this의 타입 지정??
여기서는 자바스크립트의 클래스를 타입스크립트에서는 어떻게 쓰는지 알아보겠습니다.
(참고로 자바스크립트 문법에 대해서는 깊게 다루지 않겠습니다...!)
자바스크립트와 다르게 외부에서 변경 여부에 따라 public, private,
읽기만 가능하도록 할 경우 readonly 옵션 변수 앞에 지정할 수 있습니다.
마치 다른 언어와 비슷해 보이죠?
여기서 private와 protected 둘다 외부에서 접근이 불가능하지만, protected는 상속받은 클래스끼리는 사용 가능하다는 차이가 있습니다.
그럼 이런 옵션들은 어떻게 사용하는지 클래스 프로퍼티 지정과 함께 살펴보도록 하겠습니다.
클래스의 constructor에 들어갈 프로퍼티의 타입은 어떻게 정할까요?
아래의 예제처럼 constructor이전, 바깥에 정의할 수 있습니다.
class Car{
private readonly id: number;
private name: string; //public은 기본값이므로 따로 적지 않아도 됩니다.
constructor(){
this.id=id;
this.name=name;
}
}
constructor에 사용하는 프로퍼티라면,
위 예제를 아래의 예제처럼 작성할 수도 있습니다.
뭔가 좀 더 간결해 보입니다!
class Car{
constructor(private readonly id: number, private name: string){
}
}
클래스 내의 특정 메서드에 this를 타입을 지정하듯이 지정합니다.
class Car {
private options: string[] = [];
constructor(private readonly id: number, private name: string) {
}
//()안에 이 메서드의 this 타입을 명시해 줍니다.
printCar(this: Car) {
console.log(`Car: [id: ${this.id}] ${this.name}`);
}
addOptions(option: string) {
this.options.push(option);
}
}
const myCar1 = new Car(001, "AutoBot");
myCar1.addOptions("Navigation");
오늘은 Typescript를 작성할 때 class는 어떻게 사용하는지 살펴보았습니다.
저는 다음 시간에도 살아남을 수 있을까요?!