面试题答案
一键面试- 定义元数据结构:
首先定义用于存储类和方法文档元数据的结构。
interface MethodDocMeta { description: string; parameters: { name: string; type: string; description: string }[]; returns: { type: string; description: string }; } interface ClassDocMeta { description: string; methods: { [methodName: string]: MethodDocMeta }; }
- 类装饰器:
用于为类添加描述信息,并初始化方法元数据的容器。
function classDocumenter(description: string) { return function (target: Function) { Reflect.defineMetadata('class:doc', description, target); Reflect.defineMetadata('class:methods', {}, target); }; }
- 方法装饰器:
为方法添加详细的文档元数据。
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); }; }
- 示例类及使用:
@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; } }
- 生成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文档。