Typescript 클래스와 인터페이스

HOONEY·2022년 6월 20일
0

Typescript

목록 보기
7/7
post-thumbnail

Classes

abstract class User { // 인스턴스 생성 불가 
	constructor (
    	private firstName: string,
        protected lastName: string,
        public nickName: string
    ) {}
    // 추상 메소드는 추상 클래스를 상속받는 클래스들이 반드시 구현(implement)해야하는 메서드.
    abstract getNickName(): void  
    getFullName() {
    	return `${this.firstName} ${this.lastName}`;
    }
}

class Player extends User {
	getNickName() {
    	console.log(this.lastName); // protectd, public은 접근 가능
    }
}

const test = new Player("f", "l", "n");
test.firstName; // error
test.nickName; // public이기 때문에 no error

const user = new User("f", "l", "n") // 추상클래스이기 때문에 error
test.getFullName(); // private, protected이면 error
  • 추상클래스는 상속 받아 사용
  • 추상메소드는 추상클래스를 상속 받는 경우 항상 사용
  • private은 선언한 클래스 내에서만 사용 가능
  • protected는 선언한 클래스, 상속 받은 클래스 내에서만 사용 가능

Interfaces

  • class 복습
type Words = {
	[key: string]: string
}

class Dict {
	private words: Words
    constructor() {
    	this.words = {}
    }
    add(word: Word) {
    	if (this.words[word.term] === undefined) {
        	this.word[word.term] = word.def;
        }
    }
    def(term:string) {
    	return this.words[term];
    }
    // static은 JS
    static hello() { 
    	return "hello";
    }
}

class Word {
	constructor(
    	public readonly term: string, 
        public readonly def: string
    ) {}
}

const kimchi = new Word("kimchi", "한국음식");

const dict = new Dict()
dict.add(kimchi);
dict.def("kimchi");
  • 인터페이스: 객체의 모양을 특정해주기 위한 용도
  • 타입: 인터페이스 이외의 상황에서 사용
type Team = "red" | "blue" | "yellow";
type Health = 1 | 5 | 10

interface Player {
	nickname: string,
    team: Team,
    health: Health
}

const test: Player = {
	nickname: "테스트",
    team: "red",
    health: 10
}

interface vs type

  • 인터페이스는 타입스크립트에게 객체의 모양을 특정해준다.
interface User {
	name: string
}

interface Player extends User {

}

const test: Player = {
	name: "test"
}
  • 타입을 사용한 코드.
type User = {
	name: string
}

type Player = User & {

}

const test: Player = {
	name: "test"
}

abstract vs interface

  • abstract
abstract class User {
	constructor(
    	protected firstName: string,
        protected lastName: string
    ) {}
    abstract sayHi(name: string): string
    abstract fullName(): string
}

// new User(); // Error!

class Player extends User {
	fullName() {
    	return `${this.firstName} ${this.lastName}`;
    }
    sayHi(name: string) {
    	return `Hello ${name}.`;
    }
}
  • interface
interface User {
	firstName: string,
    lastName: string
    sayHi(name: string): string
    fullName(): string
}

interface Human {
	health: number
}

class Player implements User, Human { // 상속할 때 private, protected을 사용하지 못한다.
	constructor(
    	public firstName: string,
        public lastName: string,
        public health: number
    ) {}
    fullName() {
    	return `${this.firstName} ${this.lastName}`;
    }
    sayHi(name: string) {
    	return `Hello ${name}.`;
    }
}

Polymorphism

interface SStorage<T> {
	[key: string]: T
}

class LocalStorage<T> {
	private storage: SStorage<T> = {}
    set(key: string, value: T) {
    	this.storage[key] = value;
    }
    remove(key: string) {
    	delete this.storage[key]
    }
    get(key: string): T {
    	return this.storage[key]
    }
    clear() {
    	this.storage = {}
    }
}

const stringsStorage = new LocalStorage<string> ();

stringsStorage.get("key");
stringsStorage.set("hello", "hi");

const booleansStorage = new LocalStorage<boolean> ();

booleansStorage.get("QWE");
booleansStorage.set("hello", true);
profile
기록하는 블로그

0개의 댓글