MST

星途 面试题库

面试题:TypeScript 装饰器与元编程的深度结合

在TypeScript中,结合装饰器与元编程概念,实现一个复杂的功能:通过装饰器为类及其方法生成详细的文档元数据,并在运行时能够根据这些元数据自动生成API文档。要求设计合理的元数据结构,并处理好装饰器在不同作用域(类、方法)下的逻辑。
11.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 定义元数据结构: 首先定义用于存储类和方法文档元数据的结构。
    interface MethodDocMeta {
        description: string;
        parameters: { name: string; type: string; description: string }[];
        returns: { type: string; description: string };
    }
    
    interface ClassDocMeta {
        description: string;
        methods: { [methodName: string]: MethodDocMeta };
    }
    
  2. 类装饰器: 用于为类添加描述信息,并初始化方法元数据的容器。
    function classDocumenter(description: string) {
        return function (target: Function) {
            Reflect.defineMetadata('class:doc', description, target);
            Reflect.defineMetadata('class:methods', {}, target);
        };
    }
    
  3. 方法装饰器: 为方法添加详细的文档元数据。
    function methodDocumenter(
        description: string,
        parameters: { name: string; type: string; description: string }[],
        returns: { type: string; description: string }
    ) {
        return function (target: Object, propertyKey: string | symbol) {
            const classMeta = Reflect.getMetadata('class:methods', target.constructor) || {};
            classMeta[propertyKey.toString()] = {
                description,
                parameters,
                returns
            };
            Reflect.defineMetadata('class:methods', classMeta, target.constructor);
        };
    }
    
  4. 示例类及使用
    @classDocumenter('This is a sample class for demonstration.')
    class SampleClass {
        @methodDocumenter(
            'This method adds two numbers.',
            [
                { name: 'a', type: 'number', description: 'The first number.' },
                { name: 'b', type: 'number', description: 'The second number.' }
            ],
            { type: 'number', description: 'The sum of a and b.' }
        )
        add(a: number, b: number): number {
            return a + b;
        }
    }
    
  5. 生成API文档: 在运行时,根据元数据生成API文档。
    function generateAPIDoc(target: Function): ClassDocMeta {
        const classDescription = Reflect.getMetadata('class:doc', target);
        const methodMeta = Reflect.getMetadata('class:methods', target);
        return {
            description: classDescription || '',
            methods: methodMeta || {}
        };
    }
    
    const doc = generateAPIDoc(SampleClass);
    console.log(doc);
    

这样,通过上述装饰器和元编程的结合,我们可以为类及其方法生成详细的文档元数据,并在运行时生成API文档。