제네릭은 선언 시점이 아니라 생성 시점에 타입을 명시하여 하나의 타입만이 아닌 다양한 타입을 사용할 수 있도록 하는 기법이다. 한 번의 선언으로 다양한 타입에 재사용이 가능하다는 장점이 있다.
T 는 제네릭을 선언할때 관용적으로 사용되는 식별자입니다.
타입을 지정할때
any
를 넣기 싫을때 넣기위해?
function test<T1, T2> (a: T1, b: T2) {
return {
...a,
...b
};
}
const tested = test({ math: 1, science: 3 }, { computer: 2 });
interface Test<T, V> {
num: T[];
str: V;
}
const test: Test<number, string> = {
num: [1, 2, 3],
str: "string"
};
class Queue<T> {
list: T[] = [];
get length() {
return this.list.length;
}
enQueue (item: T) {
this.list.push(item)
}
deQueue () {
return this.list.shift();
}
}
const queue = new Queue<number>();
queue.enQueue(0);
queue.enQueue(1);
queue.enQueue(2);
queue.enQueue(3);
queue.enQueue(4);
while (queue.length > 0) {
console.log(queue.dequeue());
}
// 0
// 1
// 2
// 3
// 4