클래스 선언
class Car {
color: string; //타입스크립트에서 클래스를 작성할 때, 멤버변수 미리 선언 해 줘야한다.
//멤버변수를 미리 선언하지 않을 때, 접근제한자, readonly 키워드 이용
//constructor(public color: string) {
//constructor(readonly color: string) {
constructor(color: string) {
this.color = color;
}
start() {
console.log("start");
}
}
const bmw = new Car("Red");
접근 제한자
public : 자식 클래스 , 클래스 인스턴스 모두 접근 가능
private : private라면 자식 클래스 내부에서 사용할 수 없다. 앞에 #을 붙여도 private이다. 해당 클래스 내부에서만 접근 가능
protected : 자식클래스 내부에서는 접근 가능, 클래스 인스턴스로는 접근 불가
//접근 제한자 (Access modifier) - public, private, protected
class Car {
name: string = "car";
color: string;
constructor(color: string) { //인스턴스 객체를 초기화할 때 수행할 초기화 코드를 정의
this.color = color;
}
start() {
console.log("start");
}
}
class Bmw extends Car {
//car 클래스를 상속받은 Bmw
constructor(color: string) { //부모 클래스의 생성자를 호출
super(color); //super 호출 ,자신의 매개변수를 부모 클래스의 생성자로 전달
}
showName() {
console.log(super.name);
}
}
const z4 = new Bmw("black");
console.log(z4);
읽기전용 property
name에 readonly를 붙여주면 수정할 수 없게 된다.
만약 위와같은 상황에서 name을 바꾸고 싶다면, constructor내부에서 작업을 해준다.
class Car {
readonly name: string = "car";
color: string;
constructor(color: string, name: string) {
this.color = color;
this.name = name;
}
start() {
console.log("start");
}
}
class Bmw extends Car {
//car 클래스를 상속받은 Bmw
constructor(color: string, name: string) {
super(color, name);
}
showName() {
console.log(super.name);
}
}
const z4 = new Bmw("black", "adfg");
//z4.name = "1111"
static
정적 멤버변수를 만들 수 있다.
static으로 선언된 정적 멤버변수나 메서드는 this를 사용하는 것이 아닌, 클래스 명을 적어준다.
//접근 제한자 (Access modifier) - public, private, protected
class Car {
readonly name: string = "car";
color: string;
static wheels = 4;
constructor(color: string, name: string) {
this.color = color;
this.name = name;
}
start() {
console.log("start");
}
}
class Bmw extends Car {
//car 클래스를 상속받은 Bmw
constructor(color: string, name: string) {
super(color, name);
}
showName() {
console.log(super.name);
}
}
const z4 = new Bmw("black", "adfg");
console.log(Car.wheels);
추상 class
클래스 앞에 abstract 키워드를 사용한다.
추상클래스는 new를 이용해서 객체를 만들 수 없다. 상속을 통해서만 사용이 가능하다.
추상클래스 내부에 추상 메소드는 반드시 상속받은 쪽에서 구현을 해줘야한다.
추상화는 프로퍼티나 메소드의 이름만 선언해주고 구체적인 기능은 상속 받는 쪽에서 구현해주는 것을 의미한다.
추상클래스는 상속받아 만든 수많으 객체들이 동일하게 메소드를 가지고 있겠지만 구체적인 기능은 가지각색일 수 있다.
abstract class Car {
color: string;
constructor(color: string) {
this.color = color;
}
start() {
console.log("start");
}
abstract doSomthing(): void;
}
//const car = new Car("red") X
class Bmw extends Car {
constructor(color: string) {
super(color);
}
doSomthing() {
console.log("do");
}
}
'Front-end > TypeScript' 카테고리의 다른 글
[TypeScript] 유틸리티 타입 Utility Types (0) | 2022.03.06 |
---|---|
[TypeScript] 제네릭 Generics (0) | 2022.03.06 |
[TypeScript ] 리터럴, 유니온/교차 타입 (0) | 2022.03.06 |
[TypeScript] 함수 (0) | 2022.03.06 |
[TypeScript] 인터페이스(interface) (0) | 2022.03.06 |