[TypeScript] 타입스크립트 Polymorphism


[TypeScript] 타입스크립트 Polymorphism

Polymorphism 콜 시그니쳐를 통하여 "number", boolean", "string"을 허용해줬지만 문제는 해당 배열에서 타입을 섞어서는 처리할 수가 없다. 왜냐하면 타입을 섞은 배열에 대한 콜 시그니쳐가 없기 때문이다. 이런 경우에는 "Polymorphism"의 "제네릭(Generic)" 이용하여 처리하면 된다. type array = { (arr: number[]): void; (arr: boolean[]): void; (arr: string[]): void; } const handler: array = (arr) => { arr.forEach(i => console.log(i)); } handler([1, 2, 3, 4]); // OK handler([true, false, true, false]); // OK handler(["a", "b", "c", "d"]); // OK handler(["a", 1, 2, false]); // ERROR 아래 처럼 제네릭 형태로...


#generic #polymorphism #typescript #제네릭

원문링크 : [TypeScript] 타입스크립트 Polymorphism