#4.Classes and interfaces

해피데빙·2022년 7월 19일
0

Typescript

목록 보기
8/9

javascript에서 사용하는 OOP를 사용할 수 있다

typescript에서 class 사용하기

typescript 코드

class Player {
	constructor(
    	private firstName:string, 
        private lastName:string,
      	public lastName:string
    ) {}
}

const nico = new Player("nico", "las", "니꼬"); 
//public인 nico.nickname만 접근 가능

javascript 코드

class Player {
	constructor(
    	this.firstName = firstName
        this.lastName = lastName
        this.nickName = nickName
}
//private, public을 정해줄 수 없다

추상 클래스

  • 다른 클래스가 상속은 할 수 있지만, 직접 인스턴스를 만들 수는 없는 클래스
  • method, property 모두 public, private 사용 가능
abstract class User{
	constructor(
    	private firstName:string, 
        private lastName:string,
      	public lastName:string
    ){}
    private getFullName(){
    	return `${this.firstName} ${this.lastNAme}`
    }
} 
//직접적으로 User를 이용할 수는 없다 
 

class Player extends User{}//이렇게 해줘야 추상 클래스를 사용할 수 있다 

const nico = new Player("nico", "las", "니꼬"); 


nico.firstName // private
nico.nickname //Public 

추상 메서드를 사용할 수 있다

abstract class User{
	constructor(	
    	private firstName:string, 
        private lastName:string,
      	public lastName:string
    ){}
    abstract getNickName():void

}
profile
노션 : https://garrulous-gander-3f2.notion.site/c488d337791c4c4cb6d93cb9fcc26f17

0개의 댓글