
사용할 일은 거의 없겠지만 JS 라이브러리나 패키지를 어떻게 TS에서 사용하는지 이해하기 좋음
1. 타입 정의를 써야하는 이유
패키지나 라이브러리, 프레임워크는 JS로 만들어져있음
그것을 TS 프로젝트에 사용하기 위해서 타입 정의로 알려줘야 함
- src내에 myPackage.js 만들기
export function init(config) { return true; } export function exit(code) { return code+1; }
- index.ts에서 사용해보기
import {init} from "myPackage";

{ "include": ["src", "src/.myPackage.js"], "compilerOptions": { "outDir": "build", "target": "ES6", "lib": ["ES6", "DOM"], "strict": true, // 매우 보호해줌 } }
2. myPackage.js 만들기

export function init(config) { return true; } export function exit(code) { return code+1; }
- 만든 패키지 사용해보기
import {init} from "myPackage";

3. myPackage.d.ts 파일 만들기

declare module "myPackage";
- myPackage가 있는 것은 알지만 init이 있는지는 모르는 상태
- d.ts의 정의 파일에서 타입만 써주면 됨
interface Config { url: string; } declare module "myPackage"{ function init(config:Config): boolean; }
- 사용 가능함
import {init} from "myPackage"; init({ url: "true" })
- exit도 사용해보기
interface Config { url: string; } declare module "myPackage"{ function init(config:Config): boolean; function exit(code:number): number; }
import {init, exit} from "myPackage"; init({ url: "true" }) exit(1)
Share article