MST

星途 面试题库

面试题:TypeScript装饰器的基本使用场景

请阐述TypeScript装饰器在实际项目中常见的至少两种使用场景,并分别给出简单示例代码说明。
16.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

1. 日志记录

在实际项目中,经常需要对方法的调用进行日志记录,以便于调试和监控。

示例代码:

function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
        console.log(`Calling method ${propertyKey} with arguments:`, args);
        const result = originalMethod.apply(this, args);
        console.log(`Method ${propertyKey} returned:`, result);
        return result;
    };
    return descriptor;
}

class MathUtils {
    @log
    add(a: number, b: number) {
        return a + b;
    }
}

const mathUtils = new MathUtils();
mathUtils.add(2, 3);

2. 权限控制

在涉及到用户权限的项目中,通过装饰器可以方便地对某些方法进行权限检查。

示例代码:

interface User {
    role: string;
}

function checkPermission(requiredRole: string) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;
        descriptor.value = function (this: User, ...args: any[]) {
            if (this.role === requiredRole) {
                return originalMethod.apply(this, args);
            } else {
                throw new Error('Permission denied');
            }
        };
        return descriptor;
    };
}

class AdminPanel {
    constructor(public user: User) {}

    @checkPermission('admin')
    deleteUser(userId: string) {
        console.log(`Deleting user with ID ${userId}`);
    }
}

const user: User = { role: 'user' };
const adminPanel = new AdminPanel(user);
try {
    adminPanel.deleteUser('123');
} catch (error) {
    console.error(error.message);
}