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)
// Export a constant
export const PI = 3.14;
// Export a function
export function add(x: number, y: number): number {
return x + y;
}app.ts (another module)
// Import PI and add from the math.ts module
import { PI, add } from './math';
console.log(PI); // 3.14
console.log(add(5, 3)); // 8Modularization 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.
// A simple function with type annotations
function greet(name: string): string {
return `Hello, ${name}`;
}
let message = greet("TypeScript");
console.log(message);3. Classes
Classes are blueprints for creating objects. They encapsulate data (properties) and methods that operate on the data.
class Greeter {
// Property
greeting: string;
// Constructor
constructor(message: string) {
this.greeting = message;
}
// Method
greet() {
return "Hello, " + this.greeting;
}
}
// Create an object instance using the class
let greeter = new Greeter("world");
console.log(greeter.greet());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.
// Define an interface
interface Person {
firstName: string;
lastName: string;
}
// Function parameter uses interface as type
function welcome(person: Person) {
return `Hello, ${person.firstName} ${person.lastName}`;
}
let user = { firstName: "Jane", lastName: "User" };
console.log(welcome(user));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.).
// Variable declaration and assignment
let a: number = 10;
const b: number = 20;
// Conditional statement
if (a < b) {
console.log("a is less than b");
}
// Loop statement
for (let i = 0; i < 3; i++) {
console.log(i);
}Combining these basic structures allows you to build feature-rich TypeScript applications.