PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

[FIXED] How to extend class type with decorator

 October 26, 2022     decorator, javascript, oop, typescript     No comments   

Issue

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

@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.

I wounder, how can I create a class decorator, that would extend parent's type. 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?


Solution

The answer is in the TypeScript docs of the Class decorators:

// 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'.


Answered By - Guerric P
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,258,854

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing