C.W.K.
Stream
Lesson 02 of 05 · published

`import type` 와 Verbatim Module Syntax

~8 min · modules, import-type, type-only

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"타입 import, 값 아님. Compiler 가 runtime 에 실제로 안 쓰는 거 erase 가능."

`import type` 가 뭐 함

import type { User } from './types' 가 타입만 import. Compile 시점에 TypeScript 가 dependency 기록. Emit 시점에 import 가 완전히 제거 — runtime 비용 없음, bundler 비용 없음, 타입만 필요했는데 우발적으로 heavy module 포함 위험 없음.

쓸 때:

  • Import 하는 게 타입 annotation 으로만 쓰임 (함수 parameter, return 타입, generic).
  • Source module 에 trigger 되길 원치 않는 side effect 있음 (예: import 시 global 등록하는 module).
  • 한 방향이 type-only 인 circular dependency 깨려고 시도.

Inline type import

TypeScript 4.5 부터 한 statement 에 값과 타입 import 섞을 수: import { Foo, type Bar } from './mod'. `type` prefix 가 개별 item 을 type-only 로 표시. 나머지가 값 import. 단일 module 이 너 필요한 runtime 값과 타입 둘 다 export 할 때 편리.

verbatimModuleSyntax (tsconfig)

`verbatimModuleSyntax` compiler 옵션 (TypeScript 5.0+) 이 import/export emission 을 predictable 하게: `import type` 와 `export type` 만 erase; 나머지 다 유지. TypeScript 의 옛 'isolated module' heuristic 이 쓰이지 않는다고 생각한 import erase 한 surprise 피함. Modern 프로젝트가 활성화 해야.

Import 가 타입-전용일 때마다 `import type` 써. Emit 된 JavaScript 가 더 lean 유지, tree-shaking 더 깨끗, circular dependency 관리 더 쉬워짐.

Code

import type — 별도와 inline 형태·typescript
// types.ts — 값과 타입 둘 다 export.
export function createUser(name: string): User { /* ... */ return {} as User }
export interface User { name: string; email: string }

// consumer.ts — 타입-전용 import.
import type { User } from './types';
import { createUser } from './types';   // 값 import — 별도

function welcome(u: User): string {     // 타입-전용 사용
  return `Welcome, ${u.name}`;
}

const u = createUser('Pippa');           // 값 사용
console.log(welcome(u));

// Inline 혼합.
import { createUser, type User } from './types';   // 같은 거 한 줄

// .js 출력 모습:
// import { createUser } from './types';
// function welcome(u) { return `Welcome, ${u.name}` }
// const u = createUser('Pippa');
// console.log(welcome(u));
// — `type` import 가 erase.

External links

Exercise

같은 module 에서 함수와 타입 둘 다 import 하는 파일 들고 와. 타입 import 를 import type (또는 inline type marker) 로 변환. Compile 된 JavaScript 출력 봐 — 함수 import 만 남는지 확인.
Hint
Before: 한 import 줄이 둘 다 cover. After: 2 줄 (하나 일반, 하나 import type) 또는 inline type marker 가진 한 줄. Emit 된 JS 가 값 import 만.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.