有关类装饰器的打字稿文档-函数返回“类扩展构造器{}”

时间:2019-05-19 20:32:44

标签: typescript typescript-decorator class-decorator

因此,我试图建立对Typescript Decorators的理解,而我一直停留在有关Class装饰器的示例上。给出的示例显示了如何通过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

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

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

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的所有方法和属性(构造函数是要修饰的类)。

相关问题