언어/TypeScript

함수 Overloading & 다형성

MellowHoney 2023. 10. 30. 20:45
728x90
반응형

Overloading

  • 동일한 이름에 매개 변수만 다른 여러 버전의 함수를 만드는 것을 함수의 오버로딩이라고 한다.
  • 파라미터의 형태가 다양한 여러 케이스에 대응하는 같은 이름을 가진 함수를 만드는 것
  • 함수의 다형성(다양한 형태)을 지원하는 것
  • function 키워드로만 함수 오버로딩을 할 수 있으며 arrow function으로는 오버로딩을 할 수 없다.

나쁜 예시

type Add = {
  (a: number, b: number) : number;
	(a: number, b: string) : number;
}

const add: Add = (a, b) => {
  if(typeof b === "string") return a;
	return a + b;
}

실제 사용

type Config = {
  path: string,
  state: object
}

type Push = {
  (path: string): void;
  (config: Config): void
}

const push: Push = (config) => {
  if(typeof config === "string") { console.log(config); }
  else {
    console.log(config.path);
  }
}

파라미터 개수가 다른 경우

type Add = {
  (a: number, b: number): number;
  (a: number, b: number, c: number): number;
}

const add:Add = (a, b, c?: number) => {
  if(c) return a + b + c;
  return a + b;
}

add(1,2);
add(1,2,3);
  • 오버로딩은 직접 작성보다는 외부 라이브러리 자주 보이는 형태

Polymorphism(다형성) / Generic

  • 여러가지 구조물
  • Generic → placeholder

Call Signatures

// 기존 방식, 좋지 않음
type SuperPrint = {
  (arr: number[]): void;
  (arr: boolean[]): void;
  (arr: string[]): void;
  (arr: (number|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, true, false])
// generic 사용
type SuperPrint = {
  < TypePlaceholder >(arr: TypePlaceholder[]): TypePlaceholdersa; 
  //TypePlaceholder 말고 다른거 사용 가능, T, V 많이 상용
}

const superPrint: SuperPrint = (arr) => arr[0];

superPrint([1, 2, 3, 4]);
superPrint([true, false, true]);
superPrint(["a", "b", "c"]);
superPrint([1, 2, true, false])
//제네릭 매개변수 여러개
type SuperPrint = {
  <T, M>(a: T[], b: M): T;
}

const superPrint: SuperPrint = (arr) => arr[0];

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

함수

function superPrint<V>(a: V[]) {
  return a[0];
}

const a = superPrint<number>([1, 2, 3, 4]); // 비추
const b = superPrint([true, false, true]);
const c = superPrint(["a", "b", "c"]);
const d = superPrint([1, 2, true, false])

객체

type Player<E> = {
  name: String;
  extraInfo: E;
}
type NicoExtra = {
  favFood: string;
}

const nico: Player<NicoExtra> = {
  name: "nico",
  extraInfo: {
    favFood: "kimchi";
  }
}

const lynn: Player<null> = {
  name: "lynn",
  extraInfo: null
}
반응형