MST

星途 面试题库

面试题:TypeScript类装饰器实现属性增强

编写一个TypeScript类装饰器,它可以增强类中的某个属性。例如,有一个`User`类,其中有`name`属性,装饰器要为该属性添加验证逻辑,确保`name`长度在3到20个字符之间,如果不符合则抛出错误。请给出完整代码。
40.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function validateName(target: any, propertyKey: string) {
    let value: string;
    const getter = function () {
        return value;
    };
    const setter = function (newValue: string) {
        if (newValue.length < 3 || newValue.length > 20) {
            throw new Error('Name length must be between 3 and 20 characters');
        }
        value = newValue;
    };
    if (delete target[propertyKey]) {
        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        });
    }
}

class User {
    @validateName
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}