使用TypeScriptinheritance不起作用浏览器端

先前对此的讨论: inheritanceTypeScript和导出的类和模块

这是从ValidatorMessage.class.ts生成的源代码:

///<reference path='./def/lib.d.ts'/> ///<reference path='./def/node.d.ts'/> var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var message = require("./Message.class"); var ValidatorMessage = (function (_super) { __extends(ValidatorMessage, _super); function ValidatorMessage() { _super.apply(this, arguments); } return ValidatorMessage; })(message.Message); exports.ValidatorMessage = ValidatorMessage; 

但是当我加载浏览器(Grunt.js合并和缩小后),我得到这个错误:

Uncaught TypeError:无法读取未定义的属性“原型”

在行后面:

 __.prototype = b.prototype, d.prototype = new __(); 

(〜ligne 6&7)

我不明白这个错误。 即使我只把从TS生成的源代码没有Grunt我得到相同的错误。

编辑

console.log(消息)

 function Message(message, data, status) { "undefined" == typeof data && (data = !1), "undefined" == typeof status && (status = !1), /** * Constants. */ this.FIELD_NAME_MESSAGE = "m", this.FIELD_NAME_DATA = "d", this.FIELD_NAME_STATUS = "s", this.EXCEPTION_BAD_JSON_CONTENT = 'Unable to parse JSON. Bad object/string attributes. (Missing message ("' + this.FIELD_NAME_MESSAGE + '" field) or status ("' + this.FIELD_NAME_MESSAGE + '" field)?', this.EXCEPTION_BAD_JSON_TYPE = "Incorrect data type. Object or string expected.", this._message = message, this._data = data, this._status = status; } 

由于您正在编译浏览器端,您需要使用--module amd选项进行编译。 你似乎用--module commonjs编译,这对浏览器目标是无效的。

请参阅: http : //www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

两年前我解决了这个问题。

这是因为我的ValidatorMessageinheritance了我的Message类,但加载顺序是错误的。

我正在使用CommonJS (现在仍然是这样,AMD通过使所有asynchronous和强制使用像requireJS这样的额外工具来吸引IMO,并且如果您想在服务器和浏览器上共享源代码,最好不要使用AMD,因为它实际上不是在节点。)这是为节点,但也是浏览器 – complient(如果您加载文件以正确的顺序…)

使用WebStorm IDE,我首先解决了编译AMD和CommonJS的问题,方法是使用两个“Watch任务”,一个用于CommonJS,一个用于AMD,另一个用于不同的文件集。 但后来我开始使用grunt-ts作为@basarat说,这有诀窍。

如果你正在阅读这个 ,我build议不要使用IDE观察者,而是使用grunt-ts和[tsconfig.json][1]文件。 这是我find的最好/最干净的解决scheme。 grunt-ts通过遵循tsconfig文件中的规则来完成编译工作。 (文件顺序,目标等)


原始答案:

我为WebStorm IDE(7.0)编写了一个文档,可能与6.x版本和下一个版本相同。

如果你不使用WebStorm,你可能在Visual Studio中使用TypeScript,我希望有一些插件可以做同样的事情。 应该存在。 如果你不使用VS,你应该明确地使用WebStorm作为IDE,这是我使用过的最好的。

本文档展示了如何通过编译两个不同的目标来解决我的问题。

configurationWebStorm为AMD和CommonJs编译:( 死链接) https://mega.co.nz/#!4Y8jkSwJ!BGWr2FROWYaqwdyQ4aRNczEF4bN37-EB1sO1LdVVux4

奇怪的是,打字机会这样编译它,因为它似乎通过ValidatorMessage扩展之前,甚至依赖于variables提升使其工作,这通常被认为是不好的做法。 更好的方法是:

 var ValidatorMessage = (function (_super) { function ValidatorMessage() { _super.apply(this, arguments); } __extends(ValidatorMessage, _super); return ValidatorMessage; })(message.Message);