-
Notifications
You must be signed in to change notification settings - Fork 0
04. Namespaces and Modules
idavidov13 edited this page Apr 26, 2024
·
3 revisions

- 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
- 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" />
- 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.tsUse the outFile -tsc --outFile fileName.js fileName.tsCompile the js file -node fileName
- Used to simplify the work with namespaces
- Used with import keyword
- Often used as nested namespaces
- 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
- 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
- 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 aliasD: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
- In order to compile the file we must
Compile the ts file -
tsc fileName.tsUse the outFile -tsc --module commonjs fileName.tsCompile the js file -node fileName
- 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.