Exporting and importing

The ES6 module system in TypeScript allows you to organize your code into separate files and share functionality between them using import and export statements. Here's how you can use constant exports and default exports:

1. Constant Exports

In math.ts, you have constant exports:

// math.ts
export function add(x: number, y: number): number {
    return x + y;
}

export function subtract(x: number, y: number): number {
    return x - y;
}

In main.ts, you import the add function:

// main.ts
import { add } from "./math";

console.log(add(1, 2)); // Output: 3

This imports the add function from math.ts and allows you to use it in main.ts.

2. Default Exports

In calculator.ts, you have a default export:

// calculator.ts
export default class Calculator {
    add(x: number, y: number): number {
        return x + y;
    }
}

In another file, say app.ts, you import the Calculator class using a default import:

// app.ts
import Calculator from './calculator';

const calc = new Calculator();
console.log(calc.add(10, 5)); // Output: 15

This imports the Calculator class from calculator.ts and allows you to instantiate and use it in app.ts.

Using import and export statements in TypeScript helps organize code into manageable modules and promotes reusability across your application.

Last updated

Was this helpful?