TypeScript Features
TypeScript Features
TypeScript is a superset of JavaScript that adds optional static typing to the language. This means you can write code that is more predictable and easier to maintain, while still enjoying the flexibility of JavaScript.
TypeScript provides several features that make it a powerful tool for building robust and scalable applications. Some of the key features include:
Interface
An interface defines the structure of an object. It specifies the properties and methods that an object must have. Interfaces help you define the shape of your data and make your code more readable and maintainable.
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John Doe",
age: 30
};
Class
Classes are blueprints for creating objects. They provide a way to encapsulate data and behavior, and they support inheritance and polymorphism. Classes make it easier to organize your code and create reusable components.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log("Animal is speaking");
}
}
const dog = new Animal("Buddy");
dog.speak();
Do You Know?
TypeScript supports both traditional JavaScript classes and ES6 classes.
Namespaces
Namespaces are used to group related code together. They provide a way to avoid naming conflicts and make your code more organized.
namespace Geometry {
export const PI = 3.14159;
export function calculateArea(radius: number): number {
return PI * radius * radius;
}
}
console.log(Geometry.PI);
console.log(Geometry.calculateArea(5));
Modules
Modules are self-contained units of code that can be reused in other parts of your application. They help you organize your code into smaller, more manageable chunks.
// myModule.ts
export function greet(name: string): string {
return `Hello, ${name}!`;
}
// main.ts
import { greet } from "./myModule";
console.log(greet("John"));
Important Note
Modules in TypeScript are similar to modules in JavaScript, but they provide better tooling and support for code organization.
Summary
- TypeScript adds optional static typing to JavaScript, making your code more predictable and easier to maintain.
- Interfaces define the structure of objects, helping you define the shape of your data and make your code more readable.
- Classes are blueprints for creating objects, providing a way to encapsulate data and behavior.
- Namespaces group related code together, avoiding naming conflicts and making your code more organized.
- Modules are self-contained units of code that can be reused, helping you organize your code into smaller, more manageable chunks.