아마도 처음에는 이렇게 코딩했을 것입니다. 그런데 x + y를 할 수 없다는 에러가 발생합니다. 또한 (1, 2)('1', '2')만 원했는데 (1, '2'), ('1', 2) 같은 서로 다른 타입의 값도 인수로 넣을 수 있게 됩니다. 애초에 매개변수 xy를 모두 string | number로 타이핑했기에 x가 문자열이면서 y가 숫자일 수 있게 되는 것입니다.

    이럴 때 필요한 기법이 오버로딩(overloading)입니다. 호출할 수 있는 함수의 타입을 미리 여러 개 타이핑해두는 기법입니다. 다음과 같이 코드를 변경합니다.

    function add(x: number, y: number): number
    function add(x: string, y: string): string
    function add(x: any, y: any) {
      return x + y;
    }
    
    add(1, 2); // 3
    add('1', '2'); // 12
    add(1, '2');
    add('1', 2);
    // No overload matches this call. Overload 1 of 2, '(x: number, y: number): number', gave the following error. Argument of type 'string' is not assignable to parameter of type 'number'. Overload 2 of 2, '(x: string, y: string): string', gave the following error. Argument of type 'number' is not assignable to parameter of type 'string'.
    
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.