모듈: 함수
모듈: 함수 (Module: Function)
함수 하나를 내보내는 모듈의 타입 정의를 만들 때 쓰는 템플릿이에요. 함수는 호출할 수 있는 객체이면서 동시에 속성을 가질 수 있어서, .d.ts로 옮길 때 조금 까다롭죠. 이 템플릿은 그런 함수 모듈을 어떻게 선언하는지, 오버로드(overload)와 속성까지 포함해 잡아주는 출발점입니다.
출처: TypeScript 핸드북
언제 쓰는 템플릿인가요?
다음처럼 생긴 자바스크립트 코드와 함께 작업하고 싶을 때를 떠올려 보세요.
import greeter from "super-greeter";
greeter(2);
greeter("Hello world");
이 모듈은 함수 하나를 내보내는 구조입니다. UMD를 통한 import와 일반 모듈 import를 모두 처리하려면 다음 템플릿을 쓰면 돼요.
// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ 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로 내보내는 객체가 함수라고 선언하고, declare function으로 여러 오버로드를 나열하는 방식이에요. name: string을 받으면 NamedReturnType, length: number를 받으면 LengthReturnType을 돌려주는 식으로, 인자에 따라 다른 반환 타입을 표현할 수 있죠. 함수가 가진 속성(defaultName, defaultLength)은 declare namespace Greeter 안에 멤버로 선언해 둡니다.
이 namespace 구조를 쓰면 --esModuleInterop이 켜져 있지 않을 때 모듈이 namespace 객체로 잘못 import될 수 있으니, import * as x from '...' 형태는 피해야 해요.