在TypeScript中为接口实现原型

Nic*_*kon 7 javascript interface typescript

我已经TypeScript为我的服务结果创建了一个界面。现在,我想为我的两个函数定义一个基本功能。问题是我得到一个错误:

属性“ ServiceResult”在类型“支持”的值上不存在。

我用WebStorm开发(VS2012我很紧张,因为大型项目冻结了-等待更好的集成:P)。

这是我的方法:

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

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

Support.ServiceResult.prototype.GetErrorMessage = () => {
   // (...)
};
Run Code Online (Sandbox Code Playgroud)

我也尝试将原型移到模块中,但是仍然出现相同的错误...(当然,我删除了Support.前缀)。

Fen*_*ton 7

看来您正在尝试将实现添加到接口-这是不可能的。

您只能添加到真实的实现中,例如一个类。您可能还决定只将实现添加到类定义中,而不是直接使用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 = () => {
   // (...)
};
Run Code Online (Sandbox Code Playgroud)


vcs*_*nes 6

您无法创建接口原型,因为已编译的JavaScript根本不会发出与该接口相关的任何内容。该接口仅用于编译时使用。看看这个:

此TypeScript:

interface IFoo {
    getName();
}

class Foo implements IFoo {
    getName() {
        alert('foo!');
    }
}
Run Code Online (Sandbox Code Playgroud)

编译为此JavaScript:

var Foo = (function () {
    function Foo() { }
    Foo.prototype.getName = function () {
        alert('foo!');
    };
    return Foo;
})();
Run Code Online (Sandbox Code Playgroud)

IFoo结果根本没有,这就是为什么您会收到该错误。通常,您不会原型化接口,而会原型化实现您的接口的类。

您甚至不必自己编写原型,只需将接口实现为一个类就足够了,TypeScript编译器将为您添加原型。