Typescript의 선언 방법은 아래와 같다.
Class Player {
constructor(
private firtName:string,
private lastName:string,
private nickname:string
){}
getFullName() {
return `${this.firstName} ${this.lastName}`
}
위와같이 선언할 수 있고, 컴파일 되어 아래와 같이 변경 된다.
class Player {
constructor(
//private, protected,public 자바 스크립트에선 보이지 않는다.
firstName, lastName, nickname) {
this.firstName = firstName;
this.lastName = lastName;
this.nickname = nickname;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
TS에서도 상속이 가능하다. extends
를 적어 주면 된다. extends
의 뜻은 내밀다 연장하다 확장하다 의 뜻이 존재한다. 부모의 기능을 그대로 사용할 수 있다.
class User {
constructor(
//private, protected,public 자바 스크립트에선 보이지 않는다.
private firstName:string,
private lastName: string,
private nickname: string
){}
getFirstName(){
return this.firstName
}
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
위의 코드를 보면 Player
가 User
를 상속하면서 아래와 같이User
내부의 자원을 가져다가 사용할 수 있다.
const nico = new Player("nico", "las", "니꼬");
console.log(nico.getFirstName()); //"nico"
니코를 반환 하는 것을 볼 수 있다. 여기서 함수를 사용하지 않고 바로 firstName을 가지고 오고싶겠지만, 자식이 생성자에게 접근하려 하는 순간 바로 오류가 난다. 어디 자식이 감히 아버지것을 건드렷!
그리고 추상화라는 JAVA에도 있는 클래스의 설계도와 같은 추상화가 존재한다. abstract
를 사용해주면 추상화를 TS 에서도 사용할 수 있다. abstract
로 선언한 클래스는 instance
를 생성 할 수 없다!
const ho = new User();
//User가 abstract로 만들어진경우 오류 발생한다.
abstract class User {
constructor(
//private, protected,public 자바 스크립트에선 보이지 않는다.
private firstName:string,
private lastName: string,
private nickname: string
){}
abstract getNickName():void
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
위와 같이 두면 TS 오류가 발생한다. why? abstract getNickName()
함수를 player
클래스에서 정의하지 않았기 때문이다. 꼭 정의 해줘야 한다.! 아래와 같이 정의 해보자!
abstract class User {
constructor(
//private, protected,public 자바 스크립트에선 보이지 않는다.
private firstName:string,
private lastName: string,
private nickname: string
){}
abstract getNickName():void
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
getNickName() {
console.log(this.nickname)
}
}
위와 같이 하면 오류가 발생한다. 생성자를 private
로 선언했기 때문이다. private
는 그 지역변수 안에서만 사용이 가능하다. private
, protected
, public
이렇게 세가지가 존재하고 각 역할은 아래와 같다.
그러므로 위에 코드가 정상 작동하기 위해서는 public
or protected
로 만들어야 한다.
아래 코드 처럼
abstract class User {
constructor(
private firstName:string,
private lastName: string,
protected nickname: string
){}
abstract getNickName():void
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
getNickName() {
console.log(this.nickname)
}
}
위에서 배운것을 토대로 사전을 만들어 보자.
type Words = {
[key:string]:string //key가 string인 object를 가진다는 이야기이다.
}
class Dict {
private words: Words
constructor() {
this.words = {}
}
add(word:Word){
if(this.words[word.term] === undefined) {
this.words[word.term] = word.def;
}
}
def(term:string) {
return this.words[term]
}
}
class Word {
constructor(
public readonly term:string,
public readonly def:string
)
}
const kimchi = new Word("kimchi", "한국의 음식")
kimchi.def = "한국의 최고 음식" //이런식으로 데이터에 손되면 문제가 생긴다. readonly로 막아주자.!
const dict = new Dict();
dict.add(kimchi);
dict.def("kimchi");
type
을 사용해 Words
타입을 만들었고 string
으로 이루어진 key
value
를 만들어주었다. words
를 생성하고 Word
클래스를 만들어 각 단어를 생성하고 add
메서드를 활용해서 words
생성자 에 추가해 주었다.
클래스 생성방법과 추상화 추상화 할때 부모 생성자 가져다 사용하기 등등을 알아보았다. 자주 사용해보는게 중요한거 같고 객체 지향의 개념을 머리 속에 확시하게 정립시켜야 할 거 같다.