Polymorphism(Generic)

call signature의 타입을 지정할 때 타입을 미리 하나하나 선언하는 방식으로 사용되었습니다.

*Generic을 통해 타입을 하나하나 선언하는 방식이 아닌 호출된 함수를 통해 타입을 지정하는 방식으로 사용할 수 있습니다. → 다형성(polymorphism)*

Before applying generics

// Before
type SuperPrint = {
	(arr: number[]): void
	(arr: boolean[]): void
	(arr: string[]): void
	(arr: (number|string|boolean)[]): void
}

const superPrint: SuperPrint = (arr) => {
	arr.forEach(i => console.log(i));
}

superPrint([1, 2, 3, 4]);
superPrint([true, false, true]);
superPrint(["a", "b", "c"]);
superPrint([1, 2, "3", "4", true, false]);

After applying generics

// After
type SuperPrint = {
	<T>(arr: T[]): void
}

const superPrint: SuperPrint = (arr) => {
	arr.forEach(i => console.log(i));
}

superPrint([1, 2, 3, 4]);
superPrint([true, false, true]);
superPrint(["a", "b", "c"]);
superPrint([1, 2, "3", "4", true, false]);