다형성: 다른 모양의 코드를 가질 수 있게 해주는 것 (제네릭 사용)
제네릭은 placeholder 타입을 쓸 수 있도록 해줌 (placeholder <-> concrete)
타입스크립트가 placeholder 타입을 concrete 타입으로 바꾸어줌
예제
브라우저에서 쓰는 로컬스토리지 API와 비슷한 API 만들고 타입만 넣어주기
// Storage is reserved word
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.set('hello', 'how are you')
stringsStorage.get('key')
const booleansStorage = new LocalStorage<boolean>()
booleansStorage.set('xxx', true)
booleansStorage.get('xxx')'TypeScript' 카테고리의 다른 글
| [타입스크립트] 타입스크립트 설정파일 설명 (tsconfig.json) (0) | 2022.12.07 |
|---|---|
| [타입스크립트] 빌드없이 타입스크립트 실행하기 & 서버 자동으로 재시작하기 (0) | 2022.11.29 |
| [타입스크립트] 인터페이스란? (인터페이스와 클래스의 차이점) (0) | 2022.11.17 |
| [타입스크립트] 인터페이스란? (인터페이스와 타입의 차이점) (0) | 2022.11.15 |
| [타입스크립트] 타입의 종류와 인터페이스 (0) | 2022.11.15 |
댓글