Maurizio Vacca Maurizio Vacca -4 years ago 199
TypeScript Question

Typescript: Property does not exist

I'm trying to develop a decorator for REST Api Interfaces in Typescript. Here it is the decorator implementation

export function RemoteResource(params: any): Function {
console.log("RemoteResource.params: ", params);
return function (target: Function) {

//--POST = function () {

target.prototype.retrieve = function () {

target.prototype.remove = function () {

target.prototype.update = function () {

console.log(" ", target);

return target;

Now, I can use the decorator
and the methods
are added to the original object prototype correctly.

path: "/foos",
methods: [],
requireAuth: false
export class Foo { }

From here, if I execute

let tester = new Foo(); //--This prints out "----POST" correctly

I've the log printed out correctly, but I've also have the following error: "Property 'post' does not exist on type 'Foo'."
While I understand why I'm having this error (Foo doesn't have any declared
property) I'm not sure about how to fix it.

Ideally, I would like that the TS compiler understand that the decorator extends the original object adding up those methods.

How can I achieve it? Any ideas?


Answer Source

Since you are adding these methods dynamically at runtime in the decorator, the compiler has no way of knowing that these methods will exist for Foo instances.

You can change that in different ways, for example:

(1) Using an interface and intersection:

interface RemoteResource {
    post(): void;
    remove(): void;
    update(): void;
    retrieve(): void;

let tester = new Foo() as Foo & RemoteResource;; // no error

(2) Interface and empty methods:

export class Foo implements RemoteResource {
    post: () => void;
    remove: () => void;
    update: () => void;
    retrieve: () => void;

let tester = new Foo() as Foo & RemoteResource;;


@Robba suggests:

(3) Ignore all type checking

let tester = new Foo() as any;;


let tester = new Foo();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download