Type Script Features
# Exploring TypeScript Features: A Comprehensive Guide
As developers, we continually seek ways to enhance the robustness and maintainability of our code. TypeScript, a superset of JavaScript, provides a powerful set of features that contribute to a more structured and scalable development experience. In this article, we'll delve into key TypeScript features and provide practical examples to illustrate their usage.
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John",
age: 30,
};
2. Namespaces: - Namespaces in TypeScript allow us to organize code into logical groups, preventing naming conflicts. Let's take a look at a simple example within a Geometry namespace.
namespace Geometry {
export const PI = 3.14;
export function calculateCircumference(radius: number): number {
return 2 * PI * radius;
}
}
console.log(Geometry.calculateCircumference(5)); // Output: 31.4
3. Generics:-- Generics enable the creation of flexible and reusable components. Here's a generic identity function.
function identity<T>(arg: T): T {
return arg;
}
const result: number = identity(42);
const value: string = identity("hello");
4. Abstract Classes:- Abstract classes provide a foundation for other classes and can contain abstract methods. Consider an abstract Shape class:
abstract class Shape {
abstract calculateArea(): number;
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
calculateArea(): number {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(5);
console.log(circle.calculateArea()); // Output: 78.54
5. Access Modifiers:- Access modifiers such as private, protected, and public control the visibility of class members. In the example below, the speed property is private:
领英推荐
class Car {
private speed: number;
constructor() {
this.speed = 0;
}
accelerate(): void {
this.speed += 10;
}
getSpeed(): number {
return this.speed;
}
}
const myCar = new Car();
myCar.accelerate();
console.log(myCar.getSpeed()); // Output: 10
6. Optionals:- Optionals allow the definition of properties that may or may not be present. Here's an example with an optional author property in a Book interface:
interface Book {
title: string;
author?: string;
}
const book1: Book = {
title: "The TypeScript Book",
};
const book2: Book = {
title: "JavaScript Fundamentals",
author: "John Doe",
};
7. Function Overloading:-- Function overloading allows defining multiple function signatures for a single function. TypeScript will resolve the correct signature based on the number and types of arguments provided during the function call.
function greet(name: string): string;
function greet(name: string, age: number): string;
function greet(name: string, age?: number): string {
if (age !== undefined) {
return `Hello, ${name}! You are ${age} years old.`;
} else {
return `Hello, ${name}!`;
}
}
console.log(greet("John")); // Output: Hello, John!
console.log(greet("Jane", 25)); // Output: Hello, Jane! You are 25 years old.
8. Decorators:- Decorators are a way to add metadata to classes, methods, or properties in TypeScript. They are extensively used in frameworks like Angular to enhance and modify the behavior of classes and methods.
function log(target: any, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${key} with arguments: ${JSON.stringify(args)}`);
const result = originalMethod.apply(this, args);
console.log(`Method ${key} returned: ${JSON.stringify(result)}`);
return result;
};
return descriptor;
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
const calculator = new Calculator();
console.log(calculator.add(2, 3)); // Output: Calling add with arguments: [2,3] Method add returned: 5
9. Type Utilities: TypeScript provides utility types like Partial, Pick, and Record that simplify common type manipulations. These utilities enhance code readability and maintainability by providing expressive ways to work with types.
interface User {
id: number;
name: string;
email: string;
}
type PartialUser = Partial<User>;
type RecordUser = Record<"id" | "name", string>;
const partialUser: PartialUser = { name: "John" };
const recordUser: RecordUser = { id: "1", name: "Jane" };