TypeScript: interface

Outclass·2022년 6월 9일
0

타입스크립트 TIL두번째시간은 interface!
그동안 역시나 쓴다고 써왔는데 도대체 type과의 차이가 무엇인지 제대로 이해하지 못하고 그냥 써왔다는 것을 느끼며 대충살면 안 되겠다(?)는 생각이 들었다.

기본 특성

interface Interface {
	...
}
  • 오브젝트의 모양을 특정하기 위해 사용함
  • 타입을 특정하기 위한 방법들을 사용할 수 없음
interface User {
	name: string
}

interface Player extends User {
}

const nico: Player = {
	name: "nico"
}
//타입으로 구현
type User = {
	name: string
}

type Player = User & {
}

const nico: Player = {
	name: "nico"
}
  • 클래스와 같이 상속 가능함
  • 객체지향 프로그래밍과 유사한 구조

프로퍼티의 누적

interface User {
	name: string
}
interface User {
	lastName: string
}
interface User {
	health: number
}

const nico: User = {
	name: "nico",
	lastName: "n",
	health: 10
}

다형성(Generic과 함께 사용)

//localStorage구현 예시
interface SStorage<T> {
	[key: string]: T
}

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

//사용예시
const stringsStorage = new LocalStorage<string>()
stringsStorage.set("hi", "hello") 
stringsStorage.get("hi")

그동안 정말 뭘 모르면서 코딩을 했다는 생각이 많이 들게 된다. 무엇보다 위의 localStorage 구현을 살펴보면서 프로그래밍 언어의 내부구현에 대해 어느정도 이해할 수 있는 기회가 되었다. 개인적으로는 굉장히 영감을 많이 받았다.

공부한 강의
https://nomadcoders.co/typescript-for-beginners/lobby

profile
When you stop having big dreams that’s when you’ve died, despite not being buried yet.

0개의 댓글