MST

星途 面试题库

面试题:TypeScript 复杂场景下回调中 this 类型的精准控制

在一个复杂的 TypeScript 项目中,存在一个模块 `ComplexModule`,其中有一个函数 `executeWorkflow`。`executeWorkflow` 会按照顺序执行一系列异步任务,每个任务都是通过传入回调函数来定义。这些回调函数中的 `this` 类型需要根据不同的任务阶段,有时指向 `ComplexModule` 的实例,有时指向特定的任务上下文对象(这些对象有不同的属性和方法)。请设计一个合理的类型系统和代码结构,确保 `this` 类型在各个回调函数中能被正确识别和使用,并且代码要有良好的可维护性和扩展性。请写出核心代码结构以及关键类型定义。
12.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

核心代码结构

  1. 定义 ComplexModule
class ComplexModule {
    // 假设这里有一些模块级别的属性
    moduleProperty: string;
    constructor() {
        this.moduleProperty = 'default value';
    }

    executeWorkflow() {
        // 定义一系列异步任务
        const tasks: ((this: any) => Promise<void>)[] = [];

        // 添加任务
        tasks.push(this.task1.bind(this));
        tasks.push(this.task2.bind(this));

        // 按顺序执行任务
        async function executeTasks() {
            for (const task of tasks) {
                await task();
            }
        }

        executeTasks();
    }

    task1(this: ComplexModule): Promise<void> {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log(`Task 1 in ComplexModule, moduleProperty: ${this.moduleProperty}`);
                resolve();
            }, 1000);
        });
    }

    task2(this: ComplexModule): Promise<void> {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log(`Task 2 in ComplexModule, moduleProperty: ${this.moduleProperty}`);
                resolve();
            }, 1000);
        });
    }
}
  1. 特定任务上下文对象及相关任务
// 定义特定任务上下文对象
interface TaskContext {
    contextProperty: string;
    contextMethod(): void;
}

class SpecificTaskContext implements TaskContext {
    contextProperty = 'context value';
    contextMethod() {
        console.log('Context method called');
    }
}

class ComplexModule {
    //... 前面的代码不变

    executeWorkflow() {
        const tasks: ((this: any) => Promise<void>)[] = [];
        tasks.push(this.task1.bind(this));

        const context = new SpecificTaskContext();
        tasks.push(this.taskWithContext.bind(context));
        tasks.push(this.task2.bind(this));

        async function executeTasks() {
            for (const task of tasks) {
                await task();
            }
        }

        executeTasks();
    }

    taskWithContext(this: TaskContext): Promise<void> {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log(`Task in specific context, contextProperty: ${this.contextProperty}`);
                this.contextMethod();
                resolve();
            }, 1000);
        });
    }
}

关键类型定义

  1. ComplexModule 类型
class ComplexModule {
    moduleProperty: string;
    constructor() {
        this.moduleProperty = 'default value';
    }
    // 这里可以定义更多模块级别的方法和属性
}
  1. TaskContext 类型
interface TaskContext {
    contextProperty: string;
    contextMethod(): void;
}

这样设计通过 bind 方法来确保每个回调函数中的 this 指向正确的对象,同时使用类型定义来明确 this 的类型,提高代码的可维护性和扩展性。