有人可以解释为什么this不正确吗?
又来了。
// This is defined in a d.ts file.
class Test {
someObj: {
someString: 'this'|'that'|'the other'
};
}
// This is me actually using the class.
class Test2 implements Test {
someObj = {
someString: 'this'
}
}
提前致谢:)
答案 0 :(得分:2)
这似乎是一个错误,因为即使使用extends
代替implements
它也不起作用,但这很好用:
class Test {
someObj: {
someString: 'this'|'that'|'the other'
};
}
class Test2 extends Test {
constructor() {
super();
this.someObj = {
someString: 'this'
}
}
}
两者都编译成相同的js:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Test = (function () {
function Test() {
}
return Test;
}());
var Test2 = (function (_super) {
__extends(Test2, _super);
function Test2() {
_super.call(this);
this.someObj = {
someString: 'this'
};
}
return Test2;
}(Test));
(在您的代码中除外:_super.apply(this, arguments)
)。
您可以在their github上发布问题,如果您这样做,请将该网址发布为评论,因为我想跟进。
如果您真的打算使用implements
而不是extends
,那么使用构造函数不会解决您的问题,但这样做会:
type SomeObj = {
someString: 'this'|'that'|'the other'
};
class Test {
someObj: SomeObj;
}
class Test2 implements Test {
someObj: SomeObj = {
someString: 'this'
}
}