Harangue Harangue - 3 months ago 19
TypeScript Question

TypeScript not recognizing prototype extension decorator

I'm trying to extend a class's prototype with a decorator using TypeScript's

experimentalDecorator
support.

export function Foo() {
return function (target) {
target.prototype.bar = 'baz';
}
};


While it seems that this decorator applies, TypeScript doesn't recognize the prototype extension.

@Foo()
class Qux {
constructor () {
this.bar; // Property 'style' doesn't exist on type Qux
console.log(this['bar']); // -> 'baz'
}
}


Is there a way I can get TypeScript to recognize this change that I made?

Answer

Currently there is no way to do that. There is a proposal to make type system aware of decorators, with some people saying in comments that it's hard to implement.

In the same thread you can find suggested workaround for typechecking, which uses interface merging. First, you declare an interface describing all the properties that are added by decorator (it can have the same name with the decorator):

interface Foo {
    bar: String
}

Then, for every decorated class, you declare an interface with the same name, which is merged with the class for typechecking, and typescript assumes that the interface is implemented elsewhere:

interface Qux extends Foo {}

@Foo()
class Qux {
    constructor () {
        console.log(this.bar); // -> 'baz'
    }
}