Class
- 추상 클래스: 인스턴스 생성 불가, 추상 메서드를 가질 수 있음, 상속 시 반드시 구현해야 함
- 접근제어자 -> 타입스크립트에서만 적용
- public: default
- private: 해당 클래스
- protected: 해당 클래스, 자식 클래스
abstract class User { // 추상메서드: 인스턴스 생성 불가
constructor(
protected firstName:string,
protected lastName:string,
protected nickname:string
) {}
abstract getNickName() : void // 추상메서드: 콜 시그니처만 작성
getFullName() { // private method 가능
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User{
getNickName() {
console.log(this.nickname);
}
}
const jaja = new Player("jaja", "nan", "자자");
jaja.getFullName();
//jaja.nickname; // protected는 외부에서 접근 불가능: 해당 클래스, 자식 클래스만 가능
- 클래스 활용: 사전 만들기
type Words = {
[key:string]:string // object의 type 선언, 제한된 양의 property 혹은 key를 가지는 타입을 정의
}
class Dict {
private words : Words
constructor() {
this.words = {}
}
add(word:Word) { // class를 타입으로 사용 가능
if(this.words[word.term] === undefined) {
this.words[word.term] = word.def;
}
}
def(term:string) {
return this.words[term];
}
}
class Word {
constructor(
public term:string,
public def:string
) {}
}
const kimchi = new Word("kimchi", "한국의 음식");
const dict = new Dict();
dict.add(kimchi);
dict.def("kimchi");
| [LOG]: Dict: { "words": { "kimchi": "한국의 음식" } } |
- 사전 발전시키기
type Words = {
[key:string]:string // object의 type 선언, 제한된 양의 property 혹은 key를 가지는 타입을 정의
}
class Dict {
private words : Words
constructor() {
this.words = {}
}
add(word:Word) { // class를 타입으로 사용 가능
if(this.words[word.term] === undefined) {
this.words[word.term] = word.def;
}
}
def(term:string) {
if(this.words[term] == undefined) {
return "존재하지 않는 단어";
}
return this.words[term];
}
del(term:string) {
delete this.words[term];
console.log(term+" 삭제");
}
update(word:Word) {
if(this.words[word.term] === undefined) {
return;
}
this.words[word.term] = word.def;
}
show(){
console.log(this);
}
}
class Word {
constructor(
public term:string,
public def:string
) {}
}
const kimchi = new Word("kimchi", "한국의 음식");
const dict = new Dict();
dict.add(kimchi);
console.log(dict.def("kimchi"));
const potato = new Word("potato", "구황작물");
console.log(dict.def("potato"));
dict.add(potato);
dict.show();
potato.def = "감자";
dict.update(potato);
dict.show();
dict.del("kimchi");
dict.show();
|
[LOG]: "한국의 음식"
[LOG]: "존재하지 않는 단어"
[LOG]: Dict: { "words": { "kimchi": "한국의 음식", "potato": "구황작물" } } [LOG]: Dict: { "words": { "kimchi": "한국의 음식", "potato": "감자" } } [LOG]: "kimchi 삭제" [LOG]: Dict: { "words": { "potato": "감자" } } |
'개발 > JavaScript' 카테고리의 다른 글
| [TS] 타입스크립트 프로젝트 설정 (0) | 2022.08.05 |
|---|---|
| [TS] Interfaces (0) | 2022.08.05 |
| [TypeScript] Functions (0) | 2022.08.04 |
| [TypeScript] Types (0) | 2022.08.04 |
| [Node.js] Auth route, Logout Route (0) | 2022.07.22 |