【问题标题】:Implementing prototypes for interfaces in TypeScript在 TypeScript 中为接口实现原型
【发布时间】:2013-02-26 18:03:04
【问题描述】:

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

“Support”类型的值上不存在“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 = () => {
   // (...)
};

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

【问题讨论】:

    标签: javascript interface typescript


    【解决方案1】:

    您不能对接口进行原型设计,因为编译后的 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 编译器会为您添加原型。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-06-27
        • 2021-07-20
        • 2020-08-30
        • 1970-01-01
        • 1970-01-01
        • 2016-06-20
        • 2021-10-27
        • 2015-10-08
        • 2020-04-06
        相关资源
        最近更新 更多