Table of contents

4.0. Introduction

함수는 모든 애플리케이션에서 가장 기초적인 빌딩 블록이다. 동시에 그들은 값이기도 하다. 타입스크립트는 함수가 어떻게 호출되어야 하는지에 대해 묘사하는 많은 방법들을 가지고 있다.

이제 함수 타입에는 어떤 것이 있는지 알아보자.

4.1. Function Type Expressions

함수를 표현하는 가장 간단한 방법은 *함수 타입 표현식(function type expression)*이다. 이 타입은 구문상으로 화살표 함수와 유사하다.

-function-type-exp.ts-

function greeter(fn: (a: string) => void) {
	fn('Hello, World');
}

function printToConsole(s: string) {
	console.log(s);
}

greeter(printToConsole);

(a: string) => void 는 '문자열 타입인 a라는 이름의 매개변수를 갖고, 그 반환값은 없는 함수'를 의미한다. 함수 선언문처럼, 매개변수 타입이 특정되지 않았다면, 이 매개변수의 타입은 암묵적으로 any 로 결정된다.

또한 이러한 방식의 함수 타입 지정은 타입 앨리어스에도 사용할 수 있다.

-function-type-exp-alias.ts-

type GreetFunction = (a: string) => void;
function greeterFunction(fn: GreetFunction) {
  fn('hello');
}
const greetFunc = (a: string) => console.log(a);
greeterFunction(greetFunc);

4.2. Call Signatures

자바스크립트에서, 함수 또한 오브젝트이기 때문에 호출 가능할 뿐만 아니라, 프로퍼티도 가질 수 있다. 하지만 함수 타입 표현식 문법은 그 몸체에 프로퍼티를 선언하는 것을 허용하지 않는다. 만약 우리가 프로퍼티 내에서 무언가 호출 가능한 것이 있다는 것을 묘사하려면, 오브젝트 타입 앨리어스(인터페이스)에 *호출 시그니처(Call Signature)*를 작성하면 된다.

-call-signature.ts-

type DescribableFunction = {
	description: string;
	**(someArg: number): boolean;**
};

function doSomething(fn: DescribableFunction) {
	console.log(fn.description + ' returned ' + fn(6));
}

const desFunc: DescribableFunction = (Object as any).assign(
  function (num: number) {
    return typeof num === 'number';
  },
  {
    description: 'desFunc',
  },
);
doSomething(desFunc);

위에서 살펴보았던 함수 표현식 문법과는 다소 다르다는 것을 확인하자. 호출 시그니쳐에서는 매개변수 목록과 반환 타입 사이에 기호 대신 : 를 사용하고 있다.

4.3. Construct Signatures

자바스크립트 함수는 new 키워드를 이용하여 호출할 수 있다. 일반적으로 new 키워드가 새로운 오브젝트를 생성하기 때문에, 타입스크립트는 new로 호출된 함수를 생성자로써 참조한다. 이를 표현하기 위해 호출 시그니쳐 앞에 new 키워드를 추가함으로써 *생성자 시그니처(construct signature)*를 작성할 수 있다.