※ Abstract Class/Method_ Recap
- 상속받는 Class에게 어떻게 구현해야할지는 명시하지 않지만 무엇을 구현해야 할지를 명시
- 표준화된 Property와 Method를 갖도록 하는 청사진을 위해 사용되어짐
abstract class User {
constructor(
protected firstName:string,
protected lastName: string
){}
abstract sayHi(name:string):string
abstract fullName():string
}
class Player extends User{
fullName(){
// protected는 상속받은 클래스가 property에 접근할 수 있도록 허용
return '$(this.fisrstName} ${this.lastName)'
}
sayHi(name:string){
return `Hello ${name}. My name is ${this.fullName)`
}
}
▶ Type과 Interface의 차이 (Same Code Example)
- Type과 Interface는 Object의 구조를 명시하는 동일한 작업을 수행할 수 있지만 차이점이 존재
Type | Interface |
Interface와 Type을 상속하는 방법에 차이점이 존재 | |
Interface는 정보를 축적하여 Object명시 가능 | |
컴파일 시, javascript로 변환되어 코드가 존재 | 컴파일 시, javascript로 남지 않음 -> 가벼움 |
- Type Code
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.fisrstName} ${this.lastName)'
}
sayHi(name:string){
return `Hello ${name}. My name is ${this.fullName)`
}
}
- Interface Code
interface User {
firstName:string,
protected lastName: string
sayHi(name:string):string
fullName():string
}
interface Human{
health:Number
}
// 이런식으로 여러개의 interface상속도 가능!
class Player implements User,Human{
//interface는 constructor가 없어서 하단과 같이 만들어줘야하는 번거로움
constructor(
public firstName:string.
public lastName:string,
public health.number
){}
fullName(){
return '$(this.fisrstName} ${this.lastName)'
}
sayHi(name:string){
return `Hello ${name}. My name is ${this.fullName)`
}
}
- Interface 단점
- Interface를 상속할 때에는 property를 private,protected로 만들 수 없음
- Interface는 constructor가 없어서 이렇게 만들어줘야하는 번거로움
▶ Interface +α
- argument에 interface를 넣어서 type으로 사용 가능
- argument에 인터페이스를 사용함으로써 오브젝트의 모양지정 가능
- return 도 가능
- Interface는 class return처럼 new User과 같은 구조가 아닌 그냥 하단 코드처럼 구조만 작성해주면됨
//argument, return : interface
function makeUser(user:User) : User{
return {
firstName:"yjh",
lastName:"las",
fullName:()=>"xx",
sayHi:(name)=>"string"
}
}
makeUser(
{
firstName:"yjh",
lastName:"las",
fullName:()=>"xx",
sayHi:(name)=>"string"
}
)
'Web_Study > TypeScript' 카테고리의 다른 글
TypeScript_Project1:Target (0) | 2022.07.01 |
---|---|
TypeScript_10:Summary (0) | 2022.07.01 |
TypeScript_9:Interfaces (0) | 2022.06.10 |
TypeScript_8:Class_2 (0) | 2022.06.10 |
TypeScript_7:Class (0) | 2022.06.07 |