속성을 거지는 함수 타입 정의 (정확히는 호출 시그니처(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);
