[TypeScript] 클래스

어느 개발자·2021년 4월 4일
0

TypeScript

목록 보기
3/5
post-thumbnail

ES6 표준에는 객체지향의 중요한 개념인 클래스가 추가되었다.

1. 클래스 선언

클래스는 객체를 정의하기 위한 구조이디. 클래스는 함수, 생성자, 멤버 변수로 구성된다.

클래스의 기본적인 선언 형식은 다음과 같다.

class MyClass {
	contstructor(){}
}

constructor는 생성자로서 클래스가 객체로 생성될 때 기본적으로 호출되는 메서드이다.

클래스는 그 자체로 사용할 수 없으며 객체로 만들어진 후에 사용할 수 있다. 클래스를 객체로 만들 때는 new 키워드를 이용한다.

let myClass: MyClass = new MyClass()

다음과 같이 선언과 객체 생성을 분리할 수 있다.

let myClass: MyClass
myClass = new MyClass()

자동차 클래스 선언

class MyCar {
	_numTier: number;
	_carName: string;
	
	constructor(carName: string, numTier: number) {
		this._carName = carName;
		this._numTier = numTier;
	}

	getCarName(): string {
		return this._carName;
	}

	get numTier() {
		return this._numTier;
	}
}

public 접근자를 이용해 생성자 매개변수를 전역변수로 만들기

위 코드에서 _numTier_carName을 사용하지 않고, 곧바로 생성자 매개변수를 전역화하고 싶다면 매개변수에 선언한 변수 앞에 public 접근자로 설정한다.

class MyCar {
	constructor(public carName: string, public _numTier: number){}
	
	getCarName(): string {
		return this.carName;
	}

	get numTier() {
		return this._numTier;
	}
}

생성자에 선언한 매개변수에 public을 설정하면 전역변수로 선언되는 효과가 있다.

2. 클래스 상속

타입스크립트에서는 extends 키워드를 통해 클래스 상속을 지원한다.

상속은 부모 클래스에 정의된 메서드나 변수를 자식 클래스에서 사용할 수 있게 해주는 기능이다.

class 부모클래스 {
	constructor(){}
	...
}

class 자식클래스 extends 부모클래스 {
	constructor() {
		super();
	}
}

자식 클래스의 생성자에서 super() 메서드를 이용해 상위 클래스의 생성자를 호출해야 하며, 이 메서드는 생략할 수 없다.

만약, 자식 클래스가 부모 클래스의 생성자를 호출한다면 다음과 같은 형태로 부모 클래스의 생성자로 매개변수를 전달해야 한다.

super(인자1, 인자2);

Animal 클래스를 상속하는 Monkey 클래스

class Animal {
	protected constructor(public name:string, public leg: number){}

	getLeg(): number {
		return this.leg;
	}

	protected getName(): string {
		return this.name;
	}
}

class Monkey extends Animal {
	constructor(name: string, leg: number) {
		super(name, leg);
	}
	
	isClimbing () { return true; }

	superGetName () {
		return super.getName();
	}
}

const monkey: Monkey = new Monkey("Lemur", 2);
console.log(monkey.name); // Lemur
console.log(monkey.isClimbing()); // true
console.log(monkey.getLeg()); // 2
console.log(monkey.superGetName()); // Lemur (상위 클래스의 메서드 호출)

3. 인터페이스 (interface)

타입스크립트는 인터페이스를 지원한다.

인터페이스는 인터페이스에 선언된 변수나 메서드의 사용을 구현 클래스에 강제함으로써 클래스 형태에 일관성을 유지할 수 있다는 장점이 있다.

interface 인터페이스명 {
	// 메서드나 변수 정의
}

인터페이스는 상속이 가능하다.

interface 부모인터페이스명 {
	...
}

interface 자식인터페이스명 extends 부모인터페이스명 {
	...
}

실제로 인터페이스를 클래스에서 구현하도록 가제하려면 implements 키워드를 이용하면 된다.

class 클래스명 implements 구현해야 할 인터페이스명 {
	...
}

다중 인터페이스를 상속하는 BlueBird 클래스

interface Animal {
	leg: number;
}

interface Bird extends Animal {
	wing: number;
	getNumWing();
}

class BlueBird implements Bird {
	leg: number;
	wing: number;
	constructor(leg: number, wing: number) {
		this.leg = leg;
		this.wing = wing;
	}

	getNumWing() {
		return this.wing;
	}
}

const myBlueBird = new BlueBird(2,2);
console.log(myBlueBird.getNumWing());

4. 추상 클래스

추상 클래스 (abstract class)는 구현과 강제를 동시에 수행하는 클래스이다.

추상 클래스는 abstract 키워드를 이용해 선언하며, 추상 클래스 내부에서는 추상 메서드구현 메서드로 나누어 정의한다.

추상 메서드는 abstract 키워드를 붙여서 형식만 정의하며, 구현 메서드는 abstract를 생략한 채로 정의한다.

abstract class SmallAnimals {
    abstract sound(): string;
    abstract name(): string;
    makeSound(): string {
        return `${this.name()} : ${this.sound()}`;
    }
}

class Mouse extends SmallAnimals {
    sound(): string {
        return "peep peep~";
    }
    name(): string {
        return "mouse";
    }
}

const mouse = new Mouse();
console.log(mouse.makeSound());

실행결과

타입스크립트 컴파일러로 변환된 자바스크립트 파일인 new.js 는 아래와 같다.

0개의 댓글