MST

星途 面试题库

面试题:TypeScript类装饰器@decorator的参数传递与应用

实现一个TypeScript类装饰器@validate,该装饰器接收一个字符串数组作为参数,用来验证类实例化时传入的参数类型和顺序是否与数组中定义的类型一致(假设传入参数为简单类型,如string、number等),如果不一致则抛出异常。请写出完整代码示例。
34.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
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);
}