Polymorphism in TypeScript

jisookim·2024년 10월 14일

Polymorphism : how we can write code that takes on different shapes.

generics : allows us to use placeholder types. (not concrete type)
later TypeScript will change those placeholder types to concrete types.
=> We can just use placeholder types instead of concrete types in TypeScript.


interface StorageA<T> {
	[key: string]: T;
}

class LocalStorage<T> {
	private storage: StorageA<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"); // string을 받게 될 것!
stringsStorage.set("hello", "world");

const booleanStorage = new LocalStorage<boolean>();
booleanStorage.get("key"); // boolean 받게 될 것!
booleanStorage.set("hello", true);

0개의 댓글