TypeScript
Namad TS - 4. Classes And Interfaces ②
code10
2023. 2. 25. 15:49
4.2 Interfaces
- readonly는 자바스크립트 코드에서 보이지 않아.
오브젝트의 모양을 알려주는 방법
1. 타입 설정
//string, number 로 정의하는 대신 특정 값만 갖도록 설정.
type Team = "red" | "blue" | "yellow"
type Health = 1 | 5 | 10
type Player = {
nickname: string,
team: Team,
health: Health
}
const gwen : Player = {
nickname: "Gwen",
team: "yellow",
health: 5
}
2. 인터페이스 (only 오브젝트 모양을 타입스크립트에게 설명해 주기 위해서만 사용)
type Player = {
nickname: string,
team: Team,
health: Health
}
↓↓↓인터페이스↓↓↓
interface Player {
nickname: string,
team: Team,
health: Health
}
type 키워드가 interface 키워드에 비해 좀 더 활용할 수 있는 게 많다.
(❌) interface Hello = string
인터페이스는 클래스랑 닮았다.
interface User {
name: string
}
interface player extends User {
}
const gwen : Player = {
name: "gwen"
}
||
type User = {
name: string
}
type player = User & {
}
인터페이스는 합체 능력(?)을 갖고 있다. (아래 예시에서 interface 대신 type으로는 쓸 수 없어)
interface User {
name: string
}
interface User {
nickname: string
team: number
}
const gwen : User = {
name: "gwen",
nickname: "ggg",
team: 3
}
인터페이스는 객체 지향 프로그래밍의 개념을 활용해서 디자인됨
4.3 Interfaces part Two
abstract class User {
constructor(
protected firstName:string,
protected lastName:string,
){}
abstract sayHi(name: string): string
abstract fullName(): string
}
class Player extends User {
fullName(){
return `${this.firstName} ${this.lastName}`
}
sayHi(name: string){
return `Hi ${name}. My name is ${this.fullName()}`
}
}
//표준화된 property와 메소드를 갖도록 해주는 청사진을 만들기 위해 추상클래스를 사용
//인터페이스는 컴파일하면 JS로 바뀌지 않고 사라짐.
추상 클래스를 인터페이스로
interface User {
firstName:string,
lastName:string,
sayHi(name: string): string
fullName(): string
}
interface Human {
health: number
}
class Player implements User, Human {
constructor(
public firstName:string,
public lastName:string,
public health:number
){}
fullName(){
return `${this.firstName} ${this.lastName}`
}
sayHi(name: string){
return `Hi ${name}. My name is ${this.fullName()}`
}
}
//인터페이스 상속 문제점 하나: private, protected 프로퍼티를 사용하지 못함.
4.4 Recap
타입스크립트 커뮤니티에서는 클래스나 오브젝트의 모양을 정의하고 싶으면 인터페이스를 사용하고, 다른 모든 경우에는 타입을 사용하라고 함.
Documentation - Everyday Types
The language primitives.
www.typescriptlang.org
4.5 Polymorphism (다형성)
다른 모양의 코드를 가질 수 있게 해 주는 것. 다형성을 이룰 수 잇는 방법은 제네릭을 사용하는 것. 제네릭은 placeholder 타입을 쓸 수 있도록 해줌(concrete 타입이 아니라 placeholder 타입)
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")
const booleansStorage = new LocalStorage<boolean>();
booleansStorage.get("xxx")
booleansStorage.set("hello", true)