Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing prototypes for interfaces in TypeScript

I have created a TypeScript interface for my service results. Now I want to define a basic functionality for both my functions inside. The problem is I get an error:

The property 'ServiceResult' does not exist on value of type 'Support'.

I use WebStorm for development (VS2012 makes me nervous because on freezes by large projects - waiting for better integration:P).

Here's how I do it:

module Support {
    export interface ServiceResult extends Object {
        Error?: ServiceError;
        Check?(): void;
        GetErrorMessage?(): string;
    }
}

Support.ServiceResult.prototype.Check = () => {
   // (...)
};

Support.ServiceResult.prototype.GetErrorMessage = () => {
   // (...)
};

I have also tried to move my prototypes into the module, but same error still... (of course I removed Support. prefix).

like image 840
Nickon Avatar asked Mar 11 '13 14:03

Nickon


2 Answers

You can't prototype an interface because the compiled JavaScript does not emit anything related to the interface at all. The interface exists purely for compile-time use. Take a look at this:

This TypeScript:

interface IFoo {
    getName();
}

class Foo implements IFoo {
    getName() {
        alert('foo!');
    }
}

Compiles to this JavaScript:

var Foo = (function () {
    function Foo() { }
    Foo.prototype.getName = function () {
        alert('foo!');
    };
    return Foo;
})();

There is no IFoo in the result, at all - which is why you are getting that error. Typically you wouldn't prototype an interface, you would prototype a class that implements your interface.

You don't even have to write the prototype yourself, just implementing the interface as a class is enough and the TypeScript compiler will add the prototype for you.

like image 153
vcsjones Avatar answered Sep 19 '22 08:09

vcsjones


It looks like you are trying to add implementation to an interface - which isn't possible.

You can only add to a real implementation, for example a class. You may also decide to just add the implementation to the class definition rather than directly using prototype.

module Support {
    export interface ServiceResult extends Object {
        Error?: ServiceError;
        Check?(): void;
        GetErrorMessage?(): string;
    }

    export class ImplementationHere implements ServiceResult {
        Check() {

        }

        GetErrorMessage() {
            return '';
        }
    }
}

Support.ImplementationHere.prototype.Check = () => {
   // (...)
};

Support.ImplementationHere.prototype.GetErrorMessage = () => {
   // (...)
};
like image 41
Fenton Avatar answered Sep 20 '22 08:09

Fenton