function validateUser(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const [username, password] = args;
if (username.length < 3 || username.length > 20) {
throw new Error('用户名长度必须在3到20个字符之间');
}
if (password.length < 6) {
throw new Error('密码长度至少为6个字符');
}
return originalMethod.apply(this, args);
};
return descriptor;
}
class UserRegistration {
@validateUser
register(username: string, password: string) {
console.log(`用户 ${username} 注册成功`);
}
}
// 测试
const userReg = new UserRegistration();
try {
userReg.register('test', '123456');
} catch (error) {
console.error(error.message);
}