function validate(typeArray: string[]): ClassDecorator {
return function <T extends new (...args: any[]) => any>(target: T): T {
return class extends target {
constructor(...args: any[]) {
if (args.length!== typeArray.length) {
throw new Error('参数数量不匹配');
}
for (let i = 0; i < args.length; i++) {
const expectedType = typeArray[i];
const actualType = typeof args[i];
if (actualType!== expectedType) {
throw new Error(`参数 ${i + 1} 的类型不匹配,期望 ${expectedType},实际 ${actualType}`);
}
}
super(...args);
}
}
}
}
@validate(['string', 'number'])
class ExampleClass {
constructor(public name: string, public age: number) {}
}
try {
const example = new ExampleClass('John', 30);
console.log(example);
const wrongExample = new ExampleClass(30, 'John');
} catch (error) {
console.error(error.message);
}