Skip to content

04. Namespaces and Modules

idavidov13 edited this page Apr 26, 2024 · 3 revisions

Namespaces

image

Definition

  • Namespaces are used to logically group functionalities
  • Previously referred to as internal modules in TypeScript
  • Defined with namespace keyword
  • Namespaces may include functions, classes, interfaces, and variables

Access

  • The elements of the namespace that must be accessed from the outside must be marked with export keyword
  • In order to access namespaces from different files we must use the reference syntax
    /// <reference path = "file.ts" />

Multiple Files Namespaces

  • In order to access namespaces from different files we must use the reference syntax /// <reference path = "file.ts" />
  • In order to compile the file we must

Compile the ts file - tsc fileName.ts Use the outFile - tsc --outFile fileName.js fileName.ts Compile the js file - node fileName

Aliases

  • Used to simplify the work with namespaces
  • Used with import keyword
  • Often used as nested namespaces

Modules

Definition

  • Modules are executed in their own scope, not the global
  • A set of functions to be included in applications
  • Resolve name collisions
  • In order to be accessed from the outside they need to be marked with an export keyword

Access

  • To consume a function, class, interface, or variable exported from another module we must use an import form

import { name } from "./location" - import specific element import * as variable from "./location"; - imports the entire module in single variable

Export Statements

  • There are three ways to use export statements:

A: export function numberValidation(num: number): number {…} B: export { numberValidation }; C: export { numberValidation as isValidNum }; //isValidNum is alias D: export default function stringValidations(string: string): string {…}

  • In cases A and B there is no difference rather than syntax
  • There might be only one export default in a file

Import Statements and File Compilation

  • In order to compile the file we must

Compile the ts file - tsc fileName.ts Use the outFile - tsc --module commonjs fileName.ts Compile the js file - node fileName

Namespaces vs Modules

  • Namespaces: Global containers for code organization.
  • Enclosed using namespace keyword.
  • Can be split across multiple files but combined during compilation.
  • Can contain variables, interfaces, functions, classes, etc. Modularize code into separate files.
  • Enclosed using export and import keywords.
  • Are more file-based and can be loaded asynchronously.
  • Can contain variables, functions, classes, etc., but not directly at the root level.

Clone this wiki locally