모듈: 함수
모듈: 함수 (Module: Function)
이 페이지는 "함수 하나를 내보내는 모듈"의 타입 선언 파일(.d.ts)을 몇 줄 안 되는 코드로 어떻게 써먹는지 보여주는 템플릿이에요. JavaScript 라이브러리를 만들 때 "이 라이브러리는 사실 그냥 함수 하나예요" 하는 형태라면, 이 템플릿을 그대로 붙여서 라이브러리 이름만 바꾸면 돼요. 선언 파일을 처음 쓸 때는 양식 자체가 막막한데, 이 템플릿이 그 틀을 잡아준다고 생각하면 됩니다.
출처: TypeScript 공식문서
본문
예를 들어 이런 JavaScript 코드를 다뤄야 하는 상황을 생각해 볼게요. super-greeter라는 패키지를 불러와서 함수처럼 호출하죠.
import greeter from "super-greeter";
greeter(2);
greeter("Hello world");
보면 알 수 있듯이 이 모듈은 여러 타입 인자를 받는 하나의 함수로 동작해요. 숫자를 넣으면 길이와 관련된 값을 돌려주고, 문자열을 넣으면 이름과 관련된 값을 돌려주죠. 그럼 이 녀석의 타입 선언은 어떻게 써야 할까요?
UMD를 통한 import와 일반 모듈 import를 모두 처리할 수 있도록, 아래처럼 선언 파일을 작성하면 됩니다. 이 파일을 index.d.ts로 이름을 바꾸고, 모듈 이름과 같은 폴더에 넣어주세요.
// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~]
/*~ This is the module template file for function modules.
*~ You should rename it to index.d.ts and place it in a folder with the same name as the module.
*~ For example, if you were writing a file for "super-greeter", this
*~ file should be 'super-greeter/index.d.ts'
*/
// Note that ES6 modules cannot directly export class objects.
// This file should be imported using the CommonJS-style:
// import x = require('[~THE MODULE~]');
//
// Alternatively, if --allowSyntheticDefaultImports or
// --esModuleInterop is turned on, this file can also be
// imported as a default import:
// import x from '[~THE MODULE~]';
//
// Refer to the TypeScript documentation at
// https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
// to understand common workarounds for this limitation of ES6 modules.
/*~ If this module is a UMD module that exposes a global variable 'myFuncLib' when
*~ loaded outside a module loader environment, declare that global here.
*~ Otherwise, delete this declaration.
*/
export as namespace myFuncLib;
/*~ This declaration specifies that the function
*~ is the exported object from the file
*/
export = Greeter;
/*~ This example shows how to have multiple overloads for your function */
declare function Greeter(name: string): Greeter.NamedReturnType;
declare function Greeter(length: number): Greeter.LengthReturnType;
/*~ If you want to expose types from your module as well, you can
*~ place them in this block. Often you will want to describe the
*~ shape of the return type of the function; that type should
*~ be declared in here, as this example shows.
*~
*~ Note that if you decide to include this namespace, the module can be
*~ incorrectly imported as a namespace object, unless
*~ --esModuleInterop is turned on:
*~ import * as x from '[~THE MODULE~]'; // WRONG! DO NOT DO THIS!
*/
declare namespace Greeter {
export interface LengthReturnType {
width: number;
height: number;
}
export interface NamedReturnType {
firstName: string;
lastName: string;
}
/*~ If the module also has properties, declare them here. For example,
*~ this declaration says that this code is legal:
*~ import f = require('super-greeter');
*~ console.log(f.defaultName);
*/
export const defaultName: string;
export let defaultLength: number;
}
핵심만 짚어볼게요. 함수가 모듈의 내보내기 값 그 자체라서 export = Greeter;로 "이 모듈은 Greeter라는 함수다"라고 알려줘요. 그리고 declare function을 여러 번 써서 오버로드(인자에 따라 다른 타입)를 표현하고, 반환 타입의 형태는 declare namespace Greeter 블록 안에 interface로 정리해 두는 구조예요. 이렇게 하면 함수를 호출할 때 인자 타입에 맞는 반환 타입이 자동으로 추론된답니다.
더 알아보기
- 모듈(Modules) 핸드북 — UMD import와 관련된 제약,
--esModuleInterop등 CommonJS 모듈의 동작 원리를 다룹니다. - 모듈 클래스 템플릿 — 함수가 아니라 클래스를 내보내는 모듈의 선언 양식.
- 모듈 UMD 템플릿 — 모듈 로더 밖에서 전역 변수로도 쓰이는 UMD 모듈의 선언 양식.
- 예제로 배우는 선언 파일 — 실제 사례를 통해
.d.ts를 작성하는 흐름을 봅니다.