오버로드 시그니쳐 vs 제네릭 함수

Typescript에서 함수 호출 시 그 타입을 엄격하게 제공하기 위한 2가지 방식으로 동일 사례를 예로 들어보면..

먼저 오버로드 시그니쳐의 경우입니다.

function len(s: string): number; // 오버로드 시그니쳐
function len(arr: any[]): number; // 오버로드 시그니쳐
function len(x: any): number { // 오버로드 시그니쳐
  return x.length;
}

같은 기능으로써의 제네릭 함수 방식입니다.

function len<T extends { length: number }>(x: T) {
  return x.length;
}

하지만 위와 같은 사례의 경우는 간단히 유니언 타입으로 해결이 가능합니다.

function len(x: any[] | string) {
  return x.length;
}

TypeScript에서 함수에 대한 시그니쳐

속성을 거지는 함수 타입 정의 (정확히는 호출 시그니처(call signature))

type FunctionWithProperties = {
  (someArg: number): boolean;

  description: string;
};

function doSomething(fn: FunctionWithProperties) {
  console.log(fn.description + ": 결과 = " + fn(6));
}

// 함수 생성
const isGreaterThanFive: FunctionWithProperties = (num: number) => {
  return num > 5;
};

// 속성 추가
isGreaterThanFive.description = "5보다 큰지 확인하는 함수";


// 함수 호출
doSomething(isGreaterThanFive);

클래스의 생성자에 대한 함수 타입 정의 (정확히는 생성자 시그니처(construct signature))

type SomeConstructor = {
  new (s: string): MyClass;
};

function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}

class MyClass {
  field: string = "hello";

  constructor(message: string) {
    console.log("constructor called:", message);
  }
}

const a = fn(MyClass);
console.log(a.field);

위의 2가지 요소를 조합해 보면….

interface CallOrConstruct {
  new (s: string): Date;
  (n?: number): number;
}

// 함수 객체 생성
const callOrConstruct: CallOrConstruct = function (n?: number): number {
  return n ?? 0;
} as CallOrConstruct;

// 생성자 동작 추가
callOrConstruct.prototype = Date.prototype;

// 일반 함수처럼 호출
const result = callOrConstruct(100);

console.log(result); // 100

// 생성자처럼 호출
const date = new callOrConstruct("2026-07-16");

console.log(date);
console.log(date instanceof Date);

Symbol.toPrimitive를 이용한 객체의 원시값 변환 제어

객체 자체에 대한 적절한 원시값으로 변환하고자 할때 Symbol.toPrimitive가 매우 유용하게 사용될 수 있습니다.

다음과 같은 코드가 있다면 …

const money = {
    amount: 1000,

    [Symbol.toPrimitive](hint) {
        if (hint === "number") {
            return this.amount;
        }

        return `${this.amount}원`;
    }
};

위의 money에 대해 다음 코드를 실행해 보면 상황에 맞게 해당 객체가 알맞은 원시값으로 변환되어 사용됩니다.

console.log(+money);     // 1000
console.log(`${money}`); // 1000원