Typescript Foundations / Working with Modules

Importing Types only

When you only need to import types (like interfaces, type aliases, etc.) — not actual runtime code — you can use:

import type { TypeName } from './file';

This ensures the import is erased during compilation and won’t be present in the final JavaScript output.


🔍 Why Use import type?

✅ Avoids importing unnecessary runtime code

✅ Prevents circular dependency issues

✅ Reduces bundle size in build tools like Webpack, Rollup

✅ Makes intent clearer: “I only care about the type here!”


types.ts:

export type User = {
  id: number;
  name: string;
};

export interface Product {
  id: number;
  price: number;
}

main.ts:

import type { User, Product } from './types';

const printUser = (user: User) => {
  console.log(user.name);
};

printUser({id: 1, name: "Alice"}) //Alice

✅ Output JavaScript:

No import from ./types exists in the compiled JS — it’s fully erased.


❗ Without type, what happens?

import { User } from './types';

This may generate runtime code, even though User is just a type — especially if you're using Babel or bundlers that don’t fully understand TypeScript.


🔒 When to Always Use import type

  • In libraries or packages for clean exports

  • When importing types from external dependencies (e.g., import type { FC } from 'react')

  • When separating logic and types into separate files (e.g., types.ts vs utils.ts)


🧠 Pro Tip

TypeScript 4.5+ also supports type-only re-exports:

// index.ts
export type { User, Product } from './types';

✅ Summary

Feature

import type

Used for

Type-only imports

Keeps runtime clean?

✅ Yes

Prevents circular imports

✅ Often helps

Syntax

import type { TypeName } from '...'

Supported since

TypeScript 3.8+