我有以下HTML + TypeScript试图实例化一个名为Point的简单类。单击超链接时,我会针对每个try / catch子句获得以下错误:
错误:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML App</title>
<script src="app.js"></script>
<script type="text/javascript">
function Test()
{
try { alert(MyLibrary.Point.Empty.ToString()); }
catch (e) { alert(e.message); }
try { alert(new MyLibrary.Point(10, 20).ToString()); }
catch (e) { alert(e.message); }
try { alert(MyLibrary.Point.FromPoint(new MyLibrary.Point(10, 20)).ToString()); }
catch (e) { alert(e.message); }
}
</script>
</head>
<body>
<a href="javascript:Test();">Click Me</a>
</body>
</html>
打字稿:
module MyLibrary
{
export interface IPoint { X: number; Y: number; ToString(): string; }
export class Point implements MyLibrary.IPoint
{
private _X: number = 0;
private _Y: number = 0;
constructor(x: number, y: number)
{
this._X = x;
this._Y = y;
}
public get X(): number { return (this._X); }
public get Y(): number { return (this._Y); }
public ToString(): string
{
return ("{" + this._X.toString() + "," + this._Y.toString() + "}");
}
public static FromPoint(point: MyLibrary.Point): MyLibrary.Point
{
return (new MyLibrary.Point(point.X, point.Y));
}
private static _Empty: MyLibrary.Point = new MyLibrary.Point(0, 0);
public static get Empty(): MyLibrary.Point { return (MyLibrary.Point._Empty); }
}
}
TypeScript编译正常,项目以ECMA5为目标。不知道引擎盖下发生了什么。
UPDATE :如果我从类中删除静态属性,代码就会开始工作。任何想法为什么会这样?生成的静态属性的JavaScript如下:
Object.defineProperty(Point, "Empty", {
get: function ()
{
return (MyLibrary.Point._Empty);
},
enumerable: true,
configurable: true
});
Point._Empty = new MyLibrary.Point(0, 0);
答案 0 :(得分:2)
在静态成员初始化期间,您无法引用模块内的类的限定名称 - 该类尚不可用。改变这两行:
private static _Empty: MyLibrary.Point = new MyLibrary.Point(0, 0);
public static get Empty(): MyLibrary.Point { return (MyLibrary.Point._Empty); }
到此
private static _Empty: MyLibrary.Point = new Point(0, 0);
public static get Empty(): MyLibrary.Point { return (Point._Empty); }
如果检查生成的代码,您可以看到属性MyLibrary.Point
仅在类的静态初始化发生后才设置。这可能被视为编译器错误。
答案 1 :(得分:1)
从错误消息判断模块MyLibrary是在运行时定义的,但是它内部的类Point不是。我猜测没有加载JS文件中的Point。
因为您没有使用模块,所以您要使用的每个JS文件都必须在HTML文件的顶部引用。考虑使用--out FILE
编译选项将所有类编译为单个文件,因此您只需要引用该文件。