MST

星途 面试题库

面试题:TypeScript参数装饰器在依赖注入场景的实践

在一个基于TypeScript的Web应用中,假设存在一个服务类 `UserService` 提供用户相关的操作。现在要使用参数装饰器来实现依赖注入,使得在调用某个函数处理用户业务逻辑时,可以方便地注入 `UserService` 实例。请描述整体的设计思路,并给出关键代码实现。
35.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 定义参数装饰器:用于标记需要注入 UserService 实例的参数。
  2. 创建 UserService:包含用户相关的操作方法。
  3. 实现依赖注入逻辑:在调用标记了装饰器的函数时,注入 UserService 实例。

关键代码实现

// 定义UserService类
class UserService {
    getUserInfo() {
        return "User information";
    }
}

// 定义参数装饰器
function injectUserService(target: any, propertyKey: string | symbol, parameterIndex: number) {
    const originalMethod = target[propertyKey];
    target[propertyKey] = function(...args: any[]) {
        const userService = new UserService();
        args.splice(parameterIndex, 0, userService);
        return originalMethod.apply(this, args);
    };
}

// 使用参数装饰器
class UserController {
    handleUserBusiness(@injectUserService userService: UserService) {
        return userService.getUserInfo();
    }
}

// 测试
const controller = new UserController();
console.log(controller.handleUserBusiness());