【问题标题】:Typescript Documentation on Class Decorator - function returning "class extends constructor {}"类装饰器上的打字稿文档-返回“类扩展构造函数{}”的函数
【发布时间】:2019-10-06 06:47:20
【问题描述】:

所以,我试图建立对 Typescript 装饰器的理解,但我一直停留在给出的关于类装饰器的示例上。给出的示例展示了如何通过 function(){} 形成类装饰器。

  function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T){
        return class extends constructor {
            newProperty = "new property";
            hello = "override";
        }
    }    

    @classDecorator
    class Greeter {
        property = "property";
        hello: string;
        constructor(m: string) {
            this.hello = m;
        }
    }    

    console.log(new Greeter("world"));

什么是:

return class extends constructor {
    newProperty = "new property";
    hello = "override";
}

函数如何返回扩展参数的“类”关键字(称为“构造”)?我很困惑。

这里是原始源的链接(只需滚动到类装饰器的中间部分):https://www.typescriptlang.org/docs/handbook/decorators.html

感谢任何帮助!

【问题讨论】:

    标签: typescript typescript-decorator class-decorator


    【解决方案1】:

    你需要查看装饰器的完整声明:

    function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
        return class extends constructor {
            newProperty = "new property";
            hello = "override";
        }
    }
    

    这很棘手,但这就是正在发生的事情。

    constructor 的类型是满足T 类型参数的东西。

    此类型参数T extends {new(...args:any[]):{}} 适用于任何具有构造函数的对象,该构造函数接受任意数量的任何类型的参数(即几乎任何类型)。

    这个装饰器所做的不是返回传入的constructor,而是返回一个不同的类。

    请注意,return class { ... } 语法是从函数返回匿名类的一种方式,就像 return function() { ... } 返回匿名函数一样。

    class extends constructor 表示匿名类继承了constructor 的所有方法和属性(构造函数是被修饰的类)。

    【讨论】:

    • 谢谢先生。所以使用“构造函数”作为参数名称不会违反任何规则(这将导致错误),对吗?我也可以使用任何其他词作为参数,是吗? (干杯,你的回应有帮助!)
    • 无论如何,谢谢你再次回复。我再想,我可能只需要学习更多的基础知识。 =) *干杯,
    • 是的,你可以在这个上下文中使用constructor作为参数名或变量名。
    【解决方案2】:

    对于“class extends”,它是 ES6 javascript 语法: "class expression"

    您可以在fiddle 中测试此代码:

    class Car {
        constructor(brand) {
        this.carname = brand;
      }
      present() {
        return 'I have a ' + this.carname;
      }
    }
    
    const Model = class extends Car {
      constructor(brand, mod) {
        super(brand);
        this.model = mod;
      }
      show() {
        return this.present() + ', it is a ' + this.model;
      }
    }
    
    console.log(new Model("Ford", "Mustang").show());
    

    ---结果: 《奔跑的小提琴》 “我有一辆福特,它是野马”

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 2017-05-04
      • 2017-04-02
      • 2017-01-29
      • 2015-08-10
      • 2020-08-20
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多