【问题标题】:Extended Typings on Decorated Class in TypeScriptTypeScript 中装饰类的扩展类型
【发布时间】:2018-05-08 09:33:56
【问题描述】:

这是 TypeScript 文档中有关装饰器的一些代码:

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"));

但是,如果您尝试使用 newProperty,则会收到转译器错误:

类型“Greeter”上不存在属性“newProperty”。

你如何输入这个让编译器知道newProperty实际上存在?

【问题讨论】:

    标签: typescript typescript-decorator


    【解决方案1】:

    不幸的是,装饰器不能影响使用它的类型的结构。您可以将装饰器用作一个简单的函数,并将结果用作类:

    const Greeter = classDecorator(class {
        property = "property";
        hello: string;
        constructor(m: string) {
            this.hello = m;
        }
        static test ="";
    })
    var d = new Greeter("world");
    console.log(d.newProperty);
    

    【讨论】:

      猜你喜欢
      • 2019-07-20
      • 2021-07-07
      • 1970-01-01
      • 2019-05-17
      • 2019-07-23
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 2015-10-23
      相关资源
      最近更新 更多