카테고리 없음
TypeScirpt 3
재키재키
2022. 6. 12. 16:37
1. class
- TypeScirpt에서는 private, pulbic을 지정하여 보관할 수 있다.
// class 작성 방법
class Player {
constructor(
private firstName : string,
private lastName : string,
public nickName:string
) {}
}
const joony = new Player("joony", "park", "준")
joony.nickName
// joony.firstName private 이라 접근 불가
- class 안에서 public, private, protected 키워드를 사용할 수 있고 이는 사용범위를 지정해준다.
class User {
constructor(
public firstName : string, // 어디에서든 사용가능
private lastName : string, // Property 'lastName' is private and only accessible within class 'User'
protected nickName:string // Property 'nickName' is protected and only accessible within class 'User' and its subclasses.
) {}
private getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
2. abstracn class
- 추상 클래스는 상속을 해서 사용할 수 있지만 직접적으로 인스턴스를 만들지는 못한다.
// abstract class
// 추상 클래스는 상속을 해서 사용할 수 있지만 직접적으로 인스턴스를 만들지는 못한다.
abstract class User {
constructor(
private firstName : string,
private lastName : string,
public nickName:string
) {}
private getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User{
}
// const j1oony = new User("joony", "park", "준")
// Cannot create an instance of an abstract class.
const joony = new Player("joony", "park", "준")
// joony.getFullName()
// Property 'getFullName' is private and only accessible within class 'User'
3. abstract method
- 추상 매서드는 부모로부터 상속받았을 때 반드시 구현해야하는 매서드이다.'
- 부모에서는 call signature만 정의해주면 된다,
- private을 사용하면 그 클래스를 상속받았더라도 사용할 수 없게 된다.
- protected를 사용하면 가능하다.
// abstract method
// 추상 매서는는 상속받았을때 받드시 구현을 해야하는 매서드를 의미한다.
abstract class User {
constructor(
// private을 사용하면 그 class 안에서만 사용이 가능하고
// 그 자식 class에서는 접근이 불가능하다. 이를 가능하게 하고 싶다면 대신 protected를 사용하자.
protected firstName : string,
protected lastName : string,
protected nickName:string
) {}
abstract getNickName():void
private getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
// 추상매서드를 구현해야 한다!
class Player extends User{
getNickName(){
console.log(this.lastName)
}
}