abstract class User {
constructor(
protected firstName: string,
protected lastName: string
){}
abstract sayHi(name: string): string
abstract fullName(): string
}
class Player extends User{
fullName(){
return `${this.firstName} ${this.lastName}`
}
sayHi(name: string): string{
return `Hello ${name}. My name is ${this.fullName()}`
}
}
javascript는 abstract가 없어서 단지 일반 class로 변환된다.
타입스크립트에서 클래스가 인터페이스를 상속하기 위해서 implements를 사용할 수 있다.
interface User {
firstName: string,
lastName: string
sayHi(name: string): string
fullName(): string
}
interface Human {
health: number
}
// 동시에 여러개의 interface를 상속할 수 있다.
class Player implements User, Human{
constructor(
public firstName: string,
public lastName: string,
public health: number
) {}
fullName(){
return `${this.firstName} ${this.lastName}`
}
sayHi(name: string): string{
return `Hello ${name}. My name is ${this.fullName()}`
}
}
인터페이스에서 인터페이스를 상속할 땐 extends, 클래스에서 인터페이스를 상속할 땐 implements를 사용한다.
fuction makeUser(user: User){
return "hi"
}
makeUser({
firstName: "jh",
lastName: "cha"
})
다음과 같이 인터페이스를 타입과 같이 사용할 수 있음
타입스크립트 커뮤니티에서는 클래스나 오브젝트의 모양을 정의하고 싶으면 인터페이스를 사용하고, 다른 모든 경우에서는 타입을 쓰라고 권장하고 있다.
인터페이스은 직관적인 것이 장점이고, 타입은 다른 여러 기능 (alias, 값의 제한 등)이 가능하다.