JavaScript无原生注解机制,但可通过装饰器、高阶函数或TypeScript结合class-validator模拟实现。1. 使用ES装饰器(如@validate)拦截方法调用并校验参数;2. 通过withValidation高阶函数封装校验规则,增强函数复用性;3. TypeScript项目可引入class-validator库,利用@IsString等装饰器进行DTO校验;4. 简单场景直接在函数内嵌校验逻辑。方案选择需权衡项目复杂度与技术栈。
JavaScript 没有原生的“注解”(Annotation)机制,像 Java 那样的 @Valid 或 @NotNull 注解无法直接使用。但通过一些设计模式和工具,可以模拟“注解式参数校验”,提升代码可读性和复用性。
1. 使用装饰器模拟注解行为(ES 装饰器)
虽然 JavaScript 不支持注解,但 ES 装饰器(目前处于 Stage 3)可以实现类似功能,尤其是在类方法上进行参数校验。
例如,定义一个 @validate 装饰器,自动检查函数参数是否符合规则:
function validate(target, propertyName, descriptor) { const method = descriptor.value; descriptor.value = function(...args) { // 校验逻辑:比如不允许 null 或 undefined if (args.some(arg => arg === null || arg === undefined)) { throw new Error(`调用 ${propertyName} 失败:参数不能为空`); } return method.apply(this, args); };}
使用方式:
class UserService { @validate createUser(name, age) { console.log('创建用户:', name, age); }}
注意:需启用装饰器支持(如 TypeScript 或 Babel)。
2. 自定义校验元数据 + 高阶函数模拟注解
在不使用装饰器的情况下,可以通过高阶函数封装校验逻辑,模拟“注解”效果。
定义一个校验包装器:
function withValidation(rules) { return function (targetFunc) { return function (...args) { rules.forEach((rule, index) => { if (rule.required && (args[index] === undefined || args[index] === null)) { throw new Error(`参数 ${index} 不能为空`); } if (rule.type && typeof args[index] !== rule.type) { throw new Error(`参数 ${index} 必须是 ${rule.type} 类型`); } }); return targetFunc.apply(this, args); }; };}
使用示例:
const createUser = withValidation([ { required: true, type: 'string' }, // name { required: true, type: 'number' } // age])(function(name, age) { console.log('创建用户:', name, age);});
调用时自动校验:
createUser("Alice", 25); // 正常createUser(null, 25); // 抛错
3. 利用 TypeScript + 运行时校验库(如 class-validator)
结合 TypeScript 的装饰器和 class-validator 库,能更接近“注解式校验”体验。
安装:
npm install class-validator class-transformer
示例:
import { IsString, IsInt, Min, validateSync } from 'class-validator';
class CreateUserDto { @IsString() name: string; @IsInt() @Min(0) age: number;}
function createUser(userData) { const dto = Object.assign(new CreateUserDto(), userData); const errors = validateSync(dto); if (errors.length > 0) { throw new Error('参数校验失败'); } console.log('创建用户:', dto.name, dto.age);}
这种方式结构清晰,适合大型项目或 API 接口参数校验。
4. 简化方案:函数内嵌校验或工具函数
对于小型项目,可以直接在函数开头进行参数检查,保
持简洁:
function createUser(name, age) { if (!name || typeof name !== 'string') { throw new Error('name 必须是非空字符串'); } if (typeof age !== 'number' || age
throw new Error('age 必须是大于等于 0 的数字');
}
// 正常逻辑
}
或者封装通用校验函数:
function assert(condition, message) {
if (!condition) throw new Error(message);
}
function createUser(name, age) {
assert(name && typeof name === 'string', 'name 无效');
assert(typeof age === 'number' && age >= 0, 'age 无效');
}
基本上就这些。JS 虽无原生注解,但通过装饰器、高阶函数或第三方库,完全可以实现优雅的参数校验机制。选择哪种方式,取决于项目复杂度和技术栈。