MST

星途 面试题库

面试题:TypeScript 中如何定义一个简单的类装饰器并应用元数据

请用TypeScript定义一个类装饰器,这个装饰器可以为类添加一个元数据,例如 'author' 为 'John'。同时,展示如何获取这个元数据。
13.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义一个装饰器工厂函数,用于创建装饰器
function addAuthorMetadata(author: string) {
    return function (target: Function) {
        Reflect.defineMetadata('author', author, target);
    };
}

// 使用装饰器为类添加元数据
@addAuthorMetadata('John')
class MyClass {
    // 类的具体实现
}

// 获取类的元数据
const author = Reflect.getMetadata('author', MyClass);
console.log(author); // 输出: John
  1. 装饰器工厂函数 addAuthorMetadata
    • 它接受一个 author 参数,并返回一个真正的装饰器函数。
    • 这个装饰器函数使用 Reflect.defineMetadata 方法为目标类添加 author 元数据。
  2. 使用装饰器
    • @addAuthorMetadata('John')John 作为作者元数据添加到 MyClass 类上。
  3. 获取元数据
    • 使用 Reflect.getMetadata 方法获取 MyClass 类上的 author 元数据,并输出。