Advanced Type Typescript 💻

#javascript#typescript#web
30 Jul 2023
image

TypeScript is a statically typed language that extends JavaScript by adding optional types to your code. While basic TypeScript provides powerful features like type annotations, interfaces, and type inference. This post focuses on leveraging the full potential of TypeScript's advanced type system to enhance code quality and maintainability.

1 2 3 4 5 6 7 8 // Basic TypeScript function greet(name: string): string { return `Hello, ${name}!`; } // Advanced TypeScript type Greeting = (name: string) => string; const greet: Greeting = (name) => `Hello, ${name}!`;

Advanced Type System

The Advanced TypeScript type system comprises various powerful types that allow developers to create sophisticated data structures and handle complex type transformations. Union types, intersection types, conditional types, and mapped types are some of the key features.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Union Types type Pet = "dog" | "cat" | "bird"; // Intersection Types interface Employee { id: number; name: string; } interface Role { role: string; } type EmployeeRole = Employee & Role; // Conditional Types type IsString<T> = T extends string ? true : false; type Result = IsString<string>; // Result is true // Mapped Types type Person = { firstName: string; lastName: string; }; type ReadonlyPerson = { readonly [K in keyof Person]: Person[K]; };

Generics

TypeScript generics enable writing flexible and reusable functions and classes that can work with various data types without sacrificing type safety. Generics use type parameters to create generic data structures and algorithms.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Generic Function function identity<T>(arg: T): T { return arg; } const numValue = identity<number>(42); // Type of numValue is number // Generic Class class Box<T> { value: T; constructor(value: T) { this.value = value; } } const stringBox = new Box<string>("Hello"); const numberBox = new Box<number>(42);

Enums and Literal Types

Enums provide a structured way to work with a set of constant values. Literal types allow narrowing down types based on specific values, which aids in type checking.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Enums enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE", } enum Color2 { Red, // Red = 0 Green, // Grenn = 1 Blue, // Blue = 2 } function getColorName(color: Color): string { return color; } // Literal Types type PaymentMethod = "credit_card" | "paypal" | "bank_transfer"; function processPayment(method: PaymentMethod): void { console.log(`Processing payment via ${method}`); }

Intersection Types and Mixins

Intersection types combine multiple types into a single type, enabling code reuse and extensibility. Mixins are reusable classes that can be combined with other classes.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Intersection Types interface Person { name: string; } interface Employee { role: string; } type EmployeeProfile = Person & Employee; // Mixins class Base { protected logMessage(message: string): void { console.log(`[Base]: ${message}`); } } class Timestamped extends Base { protected logMessage(message: string): void { const timestamp = new Date().toISOString(); console.log(`[Timestamped]: ${timestamp} - ${message}`); } } class ExtendedClass extends Timestamped { someMethod(): void { this.logMessage("Hello from ExtendedClass"); } } const instance = new ExtendedClass(); instance.someMethod();

Conclusion:

TypeScript offers powerful type systems, generics, enums, and additional utilities to developers. Developers may build cleaner, type-safe, and maintainable code by exploiting these capabilities. As your TypeScript expertise increases, you'll be better prepared to handle challenging development issues with confidence. Have fun coding!