Home Web Front-end JS Tutorial Advanced TypeScript: A Deep Dive into Modern TypeScript Development

Advanced TypeScript: A Deep Dive into Modern TypeScript Development

Dec 31, 2024 am 07:39 AM

Advanced TypeScript: A Deep Dive into Modern TypeScript Development

Introduction

TypeScript has become the go-to language for building scalable JavaScript applications. In this comprehensive guide, we'll explore advanced TypeScript concepts that will enhance your development skills and help you write more type-safe code.

1. Advanced Type System Features

Conditional Types

Understanding complex type relationships:

type IsArray<T> = T extends any[] ? true : false;
type IsString<T> = T extends string ? true : false;

// Usage
type CheckArray = IsArray<string[]>; // true
type CheckString = IsString<"hello">; // true

// More complex conditional types
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type ArrayElement<T> = T extends (infer U)[] ? U : never;

// Example usage
type PromiseString = UnwrapPromise<Promise<string>>; // string
type NumberArray = ArrayElement<number[]>; // number
Copy after login

Template Literal Types

Leveraging string literal types for better type safety:

type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type APIEndpoint = '/users' | '/posts' | '/comments';

type APIRoute = `${HTTPMethod} ${APIEndpoint}`;

// Valid routes
const validRoute: APIRoute = 'GET /users';
const validRoute2: APIRoute = 'POST /posts';

// Error: Type '"PATCH /users"' is not assignable to type 'APIRoute'
// const invalidRoute: APIRoute = 'PATCH /users';

// Dynamic template literal types
type PropEventType<T extends string> = `on${Capitalize<T>}`;
type ButtonEvents = PropEventType<'click' | 'hover' | 'focus'>;
// Results in: 'onClick' | 'onHover' | 'onFocus'
Copy after login

2. Advanced Generics

Generic Constraints and Defaults

Creating flexible yet type-safe generic interfaces:

interface Database<T extends { id: string }> {
    find(id: string): Promise<T | null>;
    create(data: Omit<T, 'id'>): Promise<T>;
    update(id: string, data: Partial<T>): Promise<T>;
    delete(id: string): Promise<boolean>;
}

// Implementation example
class MongoDatabase<T extends { id: string }> implements Database<T> {
    constructor(private collection: string) {}

    async find(id: string): Promise<T | null> {
        // Implementation
        return null;
    }

    async create(data: Omit<T, 'id'>): Promise<T> {
        // Implementation
        return { id: 'generated', ...data } as T;
    }

    async update(id: string, data: Partial<T>): Promise<T> {
        // Implementation
        return { id, ...data } as T;
    }

    async delete(id: string): Promise<boolean> {
        // Implementation
        return true;
    }
}
Copy after login

Mapped Types and Key Remapping

Advanced type transformations:

type Getters<T> = {
    [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};

interface Person {
    name: string;
    age: number;
}

type PersonGetters = Getters<Person>;
// Results in:
// {
//     getName: () => string;
//     getAge: () => number;
// }

// Advanced key remapping with filtering
type FilteredKeys<T, U> = {
    [K in keyof T as T[K] extends U ? K : never]: T[K]
};

interface Mixed {
    name: string;
    count: number;
    isActive: boolean;
    data: object;
}

type StringKeys = FilteredKeys<Mixed, string>;
// Results in: { name: string }
Copy after login

3. Advanced Decorators

Custom Property Decorators

Creating powerful metadata-driven decorators:

function ValidateProperty(validationFn: (value: any) => boolean) {
    return function (target: any, propertyKey: string) {
        let value: any;

        const getter = function() {
            return value;
        };

        const setter = function(newVal: any) {
            if (!validationFn(newVal)) {
                throw new Error(`Invalid value for ${propertyKey}`);
            }
            value = newVal;
        };

        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true,
        });
    };
}

class User {
    @ValidateProperty((value) => typeof value === 'string' && value.length > 0)
    name: string;

    @ValidateProperty((value) => typeof value === 'number' && value >= 0)
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}
Copy after login

4. Advanced Utility Types

Custom Utility Types

Building powerful type transformations:

// Deep Partial type
type DeepPartial<T> = {
    [P in keyof T]?: T[P] extends object
        ? DeepPartial<T[P]>
        : T[P];
};

// Deep Required type
type DeepRequired<T> = {
    [P in keyof T]-?: T[P] extends object
        ? DeepRequired<T[P]>
        : T[P];
};

// Deep Readonly type
type DeepReadonly<T> = {
    readonly [P in keyof T]: T[P] extends object
        ? DeepReadonly<T[P]>
        : T[P];
};

// Example usage
interface Config {
    server: {
        port: number;
        host: string;
        options: {
            timeout: number;
            retries: number;
        };
    };
    database: {
        url: string;
        name: string;
    };
}

type PartialConfig = DeepPartial<Config>;
// Now we can have partial nested objects
const config: PartialConfig = {
    server: {
        port: 3000
        // host and options can be omitted
    }
};
Copy after login

5. Type-Safe API Patterns

Builder Pattern with Type Safety

Implementing the builder pattern with full type safety:

class RequestBuilder<T = {}> {
    private data: T;

    constructor(data: T = {} as T) {
        this.data = data;
    }

    with<K extends string, V>(
        key: K,
        value: V
    ): RequestBuilder<T & { [key in K]: V }> {
        return new RequestBuilder({
            ...this.data,
            [key]: value,
        });
    }

    build(): T {
        return this.data;
    }
}

// Usage
const request = new RequestBuilder()
    .with('url', 'https://api.example.com')
    .with('method', 'GET')
    .with('headers', { 'Content-Type': 'application/json' })
    .build();

// Type is inferred correctly
type Request = typeof request;
// {
//     url: string;
//     method: string;
//     headers: { 'Content-Type': string };
// }
Copy after login

6. Advanced Error Handling

Type-Safe Error Handling

Creating a robust error handling system:

class Result<T, E extends Error> {
    private constructor(
        private value: T | null,
        private error: E | null
    ) {}

    static ok<T>(value: T): Result<T, never> {
        return new Result(value, null);
    }

    static err<E extends Error>(error: E): Result<never, E> {
        return new Result(null, error);
    }

    map<U>(fn: (value: T) => U): Result<U, E> {
        if (this.value === null) {
            return new Result(null, this.error);
        }
        return new Result(fn(this.value), null);
    }

    mapError<F extends Error>(fn: (error: E) => F): Result<T, F> {
        if (this.error === null) {
            return new Result(this.value, null);
        }
        return new Result(null, fn(this.error));
    }

    unwrap(): T {
        if (this.value === null) {
            throw this.error;
        }
        return this.value;
    }
}

// Usage example
function divide(a: number, b: number): Result<number, Error> {
    if (b === 0) {
        return Result.err(new Error('Division by zero'));
    }
    return Result.ok(a / b);
}

const result = divide(10, 2)
    .map(n => n * 2)
    .unwrap(); // 10
Copy after login

Conclusion

These advanced TypeScript patterns demonstrate the language's power in creating type-safe and maintainable applications. By mastering these concepts, you'll be better equipped to build robust applications that leverage TypeScript's type system to its fullest potential.

Additional Resources

  • TypeScript Documentation

  • TypeScript Deep Dive

  • TypeScript GitHub Repository

Share your experiences with these patterns in the comments below! What advanced TypeScript features have you found most useful in your projects?


Tags: #typescript #javascript #webdevelopment #programming #typing

The above is the detailed content of Advanced TypeScript: A Deep Dive into Modern TypeScript Development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles