Typescript에서 클래스는 Javascript에서 처럼 필드와 생성자의 타입만 규정해주면 된다.
class Employee {
name: string
age: number
position?: string
constructor(name: string, age: number, position: string) {
this.name = name
this.age = age
this.position = position
}
work() {
console.log('working')
}
}
Typescript의 클래스는 타입으로도 사용할 수 있다.
클래스를 타입으로 사용하면 해당 클래스가 생성하는 객체의 타입과 동일한 타입이 된다.
class Employee {
name: string
age: number
position?: string
constructor(name: string, age: number, position: string) {
this.name = name
this.age = age
this.position = position
}
work() {
console.log('working')
}
}
const employee: Employee = {
name: "park",
age: 26,
position: "dev",
work() {}
}
클래스에서의 상속은 interface와 마찬가지로 extends 키워드를 사용해 상속을 받는다.
상속받는 자식 클래스는 super()메서드를 이용해 부모 클래스의 생성자를 호출하는 방식으로 이루어진다.
class Employee {
name: string
age: number
position?: string
constructor(name: string, age: number, position: string) {
this.name = name
this.age = age
this.position = position
}
work() {
console.log('working')
}
}
class ExecutiveOfficer extends Employee {
officeNumber: number
constructor(name: string, age: number, position: string, officeNumber: number) {
super(name, age, position)
this.officeNumber = officeNumber
}
}
접근제어자는 Typescript에서 제공하는 기능으로 특정 필드나 메서드의 접근 범위를 설정하는 기능이다.
접근 제어자에는 세 가지가 있다.
public : 모든 범위에서 접근 가능private : 클래스 내부에서만 접근 가능protected : 클래스 내부 또는 파생 클래스 내부에서만 접근 가능public은 모든 범위에서 접근 가능하다.
만약 접근 제어자를 설정하지 않으면, 기본으로 public으로 설정된다.
class Employee {
public name: string
public age: number
public position: string
...
}
const employee = new Employee("Park", 26, "dev")
employee.name = "Kim"
employee.age = 25
employee.position = "qa"
private는 클래스 내부에서만 접근 가능하다.
class Employee {
private name: string // private
public age: number
public position: string
...
work() {
console.log(`${this.name} working`) // 클래스 내부에서는 접근 가능
}
}
const employee = new Employee("Park", 26, "dev")
employee.name = "Kim" // error
protected는 클래스 내부 또는 파생 클래스에서 접근 가능하다.
class Employee {
private name: string // private
protected age: number // protected
public position: string
...
}
class ExecutiveOfficer extends Employee {
...
func() {
this.name // error : private는 해당 클래스 내부에서만 접근 가능
this.age // protected는 파생 클래스 내부에서도 사용 접근
}
}
const employee = new Employee("Park", 26, "dev")
employee.name = "Kim" // error : private
employee.age = 25 // error : protected
constructor()의 매개변수에 접근제어자를 설정하면, 자동으로 필드도 함께 선언되기 때문에 필드를 작성하지 않아도 되고, this.필드 = 매개변수도 자동으로 수행된다.
class Employee {
// private name: string
// protected age: number
// public position: string
constructor(
private name: string,
protected age: number,
public position: string
) {
// this.name = name
// this.age = age
// this.position = position
}
}
Typescript의 interface는 implements키워드를 통해 class의 설계도 역할을 할 수 있다.
interface CharacterInterface {
name: string
moveSpeed: number
move(): void
}
class Character implements CharacterInterface {
constructor(
public name: string,
public moveSpeed: number,
private type: string
) {}
move(): void {
console.log(`${this.moveSpeed} 속도로 이동`)
}
}