function merge<T1, T2>(a: T1, b: T2) {
return {
...a,
...b
}
}
const merged = merge({foo: 1}, {bar: 2}); // merged에 마우스를 올리면 내부에 무엇이 있는지 볼 수 있다.
merged.foo // merged. 까지 치면 자동완성으로 내부에 있는 변수를 볼 수 있다.
즉, 어떤값이 들어올지 모를 때 any를 쓰면 변수에 마우스 올렸을 때 any 타입이라고 그대로 알려주는데 제네릭스를 쓰면 들어오는 값의 타입에 따라 동적으로 어떤 타입인지 알려준다. 아래 예를 하나 더 보자.
function wrap<T>(a: T) {
return {
a
}
}
const wrapped = wrap(30);
wrapped.a
interface Items<T> {
list: T[];
}
const items: Items<string> { // 만약 Generics안에 number를 쓰게 되면 아래 문자열 배열은 빨간 줄이 뜬다.
list: ['a', 'b', 'c']
}
type Items<T> = {
list: T[];
}
const items: Items<string> {
list: ['a', 'b', 'c']
}
type Items<T, V> {
list: T[];
value: V
}
const items: Items<string, number> {
list: ['a', 'b', 'c'],
value: 1,
}
class Queue<T> {
list: T[] = [];
// constructor(public list: T[]) {
// this.list = list;
// }
enqueue(item: T) {
this.list.push(item);
}
dequeue() {
return this.list.shift();
}
}
const queue = new Queue<string>();
queue.enqueue('a');
console.log(queue.dequeue()); // a