我刚开始使用 TypeScript,我试图理解为什么以下内联对象定义不被认为是有效的。我有一个对象集合——它们的类型(对我而言)无关紧要,但它们实现了接口,因此当我遍历它们时,我知道接口方法将出现在集合中的每个对象中。
当我尝试使用实现所需方法所需的私有信息创建对象时遇到“编译器”错误:
interface Doable {
do();
}
function doThatThing (doableThing: Doable) {
doableThing.do();
}
doThatThing({
private message: 'ahoy-hoy!', // compiler error here
do: () => {
alert(this.message);
}
});
编译器错误消息是“类型参数'{ message: string, do: () => void; }'
不可分配给 Doable 类型。对象文字必须指定已知属性,并且 Doable 类型中不存在‘消息’”。请注意,如果我在函数调用之外定义对象,则会给出相同的消息,即
var thing: Doable;
thing = {
private message: 'ahoy-hoy!', // error here
do: () => {
alert(this.message);
}
};
doThatThing(thing);
如果我也添加“意外”方法,也会出现同样的错误:
doThatThing({
do: () => {
alert("ahoy hoy");
},
doSecretly: () => { // compiler error here now
alert("hi there");
}
});
我查看了 JavaScript,发现this
内联对象定义被限定为全局对象:
var _this = this; // wait, no, why!?
function doThatThing(doableThing) {
doableThing.do();
}
doThatThing({
message: 'ahoy-hoy!',
do: function () {
alert(_this.message); // uses global
}
});
我尝试在 TypeScript 中搜索有关接口的内联实现的信息,但找不到任何专门针对此问题的信息。
我可以确认“固定”编译的 JS 按预期工作:
function doThatThing(doableThing) {
doableThing.do();
}
doThatThing({
message: 'ahoy-hoy!',
do: function () {
alert(this.message);
}
});
...这对我来说很有意义,因为(据我所知)这是隐式调用 Object 构造函数,因此this
应该将范围限定为新的 Object 实例。
似乎唯一的解决方案是将每个实现声明为实现接口的类,但这感觉真的是倒退/笨拙,因为我只会有每个类的一个实例。如果与被调用函数的唯一约定是实现接口,那么为什么对象不能包含其他成员?
抱歉,结果比我预期的要长……总之,我在问:
- 为什么该内联接口实现(“匿名类”,如Java中所说)在 TypeScript 中被认为是无效的?具体来说,该编译器错误是什么意思,它可以防止什么?
- 为什么在“已编译”的 JavaScript 中生成对全局对象的范围重新分配?
- 假设这是我的错误(例如,编译器错误对于防止某些不良情况是必要的),那么真正提前显式声明一个类的唯一解决方案是这样吗?
interface Doable {
do() : void;
}
class DoableThingA implements Doable { // would prefer to avoid this ...
private message: string = 'ahoy-hoy';
do() {
alert(this.message);
}
}
class DoableThingB implements Doable { // ... as well as this, since there will be only one instance of each
do() {
document.getElementById("example").innerHTML = 'whatever';
}
}
function doThatThing (doableThing: Doable) {
doableThing.do();
}
var things: Array<Doable>;
things = new Array<Doable>();
things.push(new DoableThingA());
things.push(new DoableThingB());
for (var i = 0; i < things.length; i++) {
doThatThing(things[i]);
}
PS 今天升级到 TS 1.6 才出现编译错误,虽然 1.6 和 1.5 都出现了编译 JS 的范围错误 bug。
更新:François Cardinaux 提供了一个指向这个答案的链接,它建议使用类型断言,但这只会消除编译器错误,实际上由于范围不正确而导致逻辑错误:
interface Doable {
do();
}
function doThatThing (doableThing: Doable) {
doableThing.do();
}
doThatThing(<Doable>{ // assert that this object is a Doable
private message: 'ahoy-hoy!', // no more compiler error here
do: () => {
alert(this.message);
}
});
查看编译后的 JS,这是不正确的:
var _this = this; // very wrong, and now hidden
function doThatThing(doableThing) {
doableThing.do();
}
doThatThing({
message: 'ahoy-hoy!',
do: function () {
alert(_this.message); // s/b "this.message", which works in JS (try it)
}
});