2013-03-11 77 views
2

我为我的服务结果创建了一个TypeScript接口。现在我想为里面的两个函数定义一个基本的功能。问题是,我得到一个错误:在TypeScript中实现接口的原型

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

我用WebStorm发展(VS2012让我很紧张,因为对大项目冻结 - 等待更好的整合:P)。

这里是我如何做到这一点:

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

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

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

我也试图在我的原型移动到模块,但同样的错误还是......(当然我删除Support.前缀)。

回答

4

它看起来像你试图添加实现到接口 - 这是不可能的。

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

由于编译的JavaScript根本不会发出与接口相关的任何内容,因此无法对接口进行原型设计。该接口纯粹用于编译时使用。看看这个:

这打字稿:

interface IFoo { 
    getName(); 
} 

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

编译成这个JavaScript:

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

有一个在结果没有IFoo,在所有 - 这就是为什么您获得的错误。通常,您不会为接口创建原型,您可以为实现接口的类创建原型。

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