0
0
Typescriptprogramming~5 mins

Export syntax variations in Typescript

Choose your learning style9 modes available
Introduction

Exporting lets you share code parts so other files can use them. It helps keep code organized and reusable.

When you want to use a function from one file inside another file.
When you want to share a variable or constant across multiple files.
When you want to organize your code into modules for better structure.
When you want to export multiple things from a single file.
When you want to rename exports for clarity or to avoid name conflicts.
Syntax
Typescript
export const name = value;
export function func() {}
export class MyClass {}

const localVar = 5;
export { localVar };

export { localVar as renamedVar };

export default function() {}

export { something } from './otherFile';

export keyword makes code available outside the file.

default export means one main thing is exported from the file.

Examples
Exports a constant named pi so other files can use it.
Typescript
export const pi = 3.14;
Exports a function named greet.
Typescript
export function greet() {
  console.log('Hello!');
}
Exports secret but renames it to answer for outside use.
Typescript
const secret = 42;
export { secret as answer };
Exports a default class Person. Only one default export per file.
Typescript
export default class Person {
  constructor(name: string) {
    this.name = name;
  }
}
Sample Program

This example shows different export styles in mathUtils.ts. The main.ts file imports them all and uses them.

Typescript
// file: mathUtils.ts
export const add = (a: number, b: number) => a + b;
export const subtract = (a: number, b: number) => a - b;

const secretNumber = 7;
export { secretNumber as luckyNumber };

export default function multiply(a: number, b: number) {
  return a * b;
}

// file: main.ts
import multiply, { add, subtract, luckyNumber } from './mathUtils';

console.log(add(2, 3));
console.log(subtract(5, 1));
console.log(multiply(4, 6));
console.log(luckyNumber);
OutputSuccess
Important Notes

You can have many named exports but only one default export per file.

When importing default exports, you can choose any name you like.

Renaming exports helps avoid name clashes or clarify meaning.

Summary

Use export to share variables, functions, or classes.

Named exports let you export many things; default export is for one main thing.

You can rename exports to keep code clear and avoid conflicts.