【问题标题】:Typescript: Add interface information to class with decoratorTypescript:使用装饰器将接口信息添加到类
【发布时间】:2018-04-09 16:06:35
【问题描述】:

我有一个这样的装饰器:

export function Entity(options?: string) {
    return (target) => {
        //do something with class(target) here
    }
}

还有一个可以这样装饰的类:

@Entity({someOptions: "foobar"})
export class Product {
    id: string;
    title: string;
    price: number;
}

如何在不这样做的情况下自动强制 id:

interface EntityInterface {
    id: string;
}

@Entity({someOptions: "foobar"})
export class Product implements EntityInterface {
    id: string;
    title: string;
    price: number;
}

装饰器自动添加的接口的实现可以吗?

【问题讨论】:

    标签: typescript decorator


    【解决方案1】:

    装饰器不能改变类的结构,这是设计使然。你可以做的是使用一个以类为参数的函数,并返回一个具有额外字段的新类:

    export function Entity(options?: string) {
      return <T extends new (...args: any[]) => any>(target: T) => {
        return class extends target {
          id: string
          constructor(...args: any[]) {
            super(...args);
            this.id = options;
          }
        }
      }
    }
    
    
    export const Product = Entity("foobar")(class Product {
      public constructor(values: Partial<Product>) {
    
      }
      title: string;
      price: number;
    });
    
    let d = new Product({
      title: ""
    });
    

    您可以在函数内部派生的类中添加字段和方法,并且它将在返回的类中可用,唯一潜在的问题是字段/方法在作为参数传递给 @ 的类中不可访问987654322@

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2021-03-11
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      相关资源
      最近更新 更多