简体   繁体   English

如何使用装饰器扩展 class 类型

[英]How to extend class type with decorator

I'd like to use decorators in my project.我想在我的项目中使用装饰器。 Here's what I have written:这是我写的:

export const DetachedWindow = (options: TDetachedWindowOptions = defaultOptions) => <R extends Constructable>(Clazz: R): R => {
    const tmp = class extends Clazz {
        value = 'value';

        value2 = 'value2';

        constructor(...args: any[]) {
            super(...args);
            // <some logick>
        }
    };
    Object.defineProperty(tmp, 'name', { value: Clazz.name });
    return tmp;
};

As you see this decorators creates a few fields.如您所见,这个装饰器创建了一些字段。 But typescript can't recognize them但是typescript无法识别

@DetachedWindow({ optA: 'optA' })
export class SomeClass {
    constructor() {
        setTimeout(() => {
            console.log(this.value); // TS2339: Property 'value' does not exist on type 'SomeClass'.
        });
    }
}

It does exsist though.它确实存在。 If I add @ts-ignore before using these parameters, the code works okay.如果我在使用这些参数之前添加@ts-ignore ,代码就可以正常工作。

I wounder, how can I create a class decorator, that would extend parent's type.我 wounder,我怎样才能创建一个 class 装饰器,它会扩展父级的类型。 I tried to do something like this:我试图做这样的事情:

export const DetachedWindow = (options: TDetachedWindowOptions = defaultOptions) => <R extends Constructable>(Clazz: R): R & { value: string } => {

But it didn't help.但这没有帮助。

Any ideas?有任何想法吗?

The answer is in the TypeScript docs of the Class decorators :答案在Class 装饰器的 TypeScript 文档中:

// Note that the decorator _does not_ change the TypeScript type
// and so the new property `reportingURL` is not known
// to the type system:
bug.reportingURL;
Property 'reportingURL' does not exist on type 'BugReport'.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM