TIL
[ TypeScript ] 타입스크립트의 Polymorphism 과 Generic.
dev_gggimmmin
2024. 3. 12. 21:38
728x90
✅ Polymorphism (다형성)
type SuperPrint = {
(arr: number[]): void,
(arr: string[]): void,
(arr: boolean[]): void,
(arr: (number|string|boolean)[]): void
}
const superPrint: SuperPrint = (arr) => {
arr.forEach(e => console.log(e));
}
superPrint([1, 2, 3])
superPrint(["a", "b", "c"])
superPrint([true, false, true])
superPrint([1, "b", true])
=> 위와 같이 다양한 경우를 커버하는 함수를 작성할 때,
모든 조합의 Call Signature를 concrete type으로 적어주는 일은 번거롭다
// generic type <T> 사용
type SuperPrint = {
<T>(arr: T[]): T
}
const superPrint: SuperPrint = (arr) => arr[0]
// (arr: number[]) => number
superPrint([1, 2, 3])
// (arr: string[]) => string
superPrint(["a", "b", "c"])
// (arr: boolean[]) => boolean
superPrint([true, false, true])
// (arr: (string | number | boolean)[]) => string | number | boolean
superPrint([1, "b", true])
=> 이 때, type에 Generic을 할당하면 호출된 값으로
concrete type을 가지는 Call Signature를 역으로 보여주는 다형성(Polymorphism)을 가진다.
✅ Generics
// generics
function identity< Type >(arg: Type): Type {
return arg;
}
// 제네릭 화살표 함수 (tsx기준)
const identity = < Type extends {} >(arg: Type):Type => {
return arg;
}
let output = identity< string >("myString"); // 첫 번째 방법
let output = identity("myString"); // 두 번째 방법
=> 두 번째 방법은 type argument inference(타입 인수 유추)를 사용합니다.
즉, 컴파일러가 전달하는 인수 유형에 따라 자동으로 Type 값을 설정하기를 원합니다.
* 제네릭은 C# 이나 Java와 같은 언어에서 재사용 가능한 컴포넌트를 만들기 위해 사용하는 기법이라 하며,
단일 타입이 아닌 다양한 타입에서 작동할 수 있는 컴포넌트를 생성할 수 있다.
* 구체적인 타입을 지정하지 않고 다양한 인수와 리턴 값에 대한 타입을 처리할 수 있다.
* 타입스크립트에서 제네릭을 통해 인터페이스, 함수 등의 재사용성을 높일 수 있다.
728x90