TypeScript Basic Structure
A TypeScript program can consist of the following parts. Understanding these basic structures helps us organize and write clearer, more modular code.
1. Modules
In TypeScript, every file containing a top-level import or export is considered a module. Modules have their own scope, and variables, functions, classes, etc. inside a module are not visible outside unless you explicitly export them using export.
Other files can use the import statement to import exported content from a module.
math.ts (module)
app.ts (another module)
Modularization is the foundation for building large applications, helping with code organization, reuse, and dependency management.
2. Functions
Functions are code blocks that perform specific tasks. Functions in TypeScript can have parameters and return values, and you can specify types for them.
3. Classes
Classes are blueprints for creating objects. They encapsulate data (properties) and methods that operate on the data.
4. Interfaces
Interfaces are a powerful feature in TypeScript, used to define the "contract" or "shape" of objects. They only contain declarations of properties and methods, not implementations.
5. Variables and Statements
The core of a program consists of variables and statements.
- Variables: Used to store data. Declared using
letorconst. - Statements: Perform an action, such as variable assignment, function calls, flow control (
if,for, etc.).
Combining these basic structures allows you to build feature-rich TypeScript applications.