Typescript Foundations / Working with Modules

Exporting & Importing in Typescript

TypeScript (like modern JavaScript) supports ES Modules, enabling you to:

  • Split your code into multiple files

  • Reuse functions, classes, interfaces, types, etc.

  • Keep your project modular and maintainable


🔹 export: Making Code Available to Others

🔸 Exporting a Variable or Function

// utils.ts
export const PI = 3.14;

export function add(a: number, b: number): number {
  return a + b;
}

🔸 Exporting a Type, Interface, or Class

// models.ts
export interface User {
  id: number;
  name: string;
}

export class UserService {
  getUser(id: number): User {
    return { id, name: "Tisha" };
  }
}

🔸 Default Export

// config.ts
const API_URL = "<https://api.example.com>";
export default API_URL;

You can only have one default export per file.


🔹 import: Bringing Code into Other Files

🔸 Importing Named Exports

// main.ts
import { PI, add } from './utils';

console.log(add(PI, 2));

🔸 Importing Types and Interfaces

import { User } from './models';
const newUser: User = { id: 1, name: "Alice" };

🔸 Importing a Default Export

import API_URL from './config';
console.log(API_URL);

🔸 Importing Everything

import * as Utils from './utils';

console.log(Utils.add(10, 5));
console.log(Utils.PI);

🔸 Import with Aliases

import { add as sum } from './utils';

console.log(sum(2, 3));

🧠 Summary

Use Case

Syntax

Export named items

export const X = ...

Export a class/type

export class MyClass {}

Default export

export default something

Import named

import { X } from './file'

Import default

import X from './file'

Import everything

import * as X from './file'

Alias imports

import { X as Y } from './file'