8

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

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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 = () => {
   // (...)
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.