我一直在关注Typescript手册,但脚本崩溃的代码示例可以在这里找到:
https://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties
有人可以帮我解决这个问题吗?
{
class BeeKeeper {
hasMask: boolean;
}
class ZooKeeper {
nametag: string;
}
class Animal {
numLegs: number;
}
class Bee extends Animal {
keeper: BeeKeeper;
}
class Lion extends Animal {
keeper: ZooKeeper;
}
function createInstance<A extends Animal>(c: new () => A): A {
return new c();
}
createInstance(Lion).keeper.nametag; // typechecks!
// createInstance(Lion).keeper.hasMask; // error!
createInstance(Bee).keeper.hasMask; // typechecks!
}
这是在TS中编译的代码块:
{
var createInstance = function createInstance(c) {
return new c();
};
var BeeKeeper = function BeeKeeper() {
_classCallCheck(this, BeeKeeper);
};
var ZooKeeper = function ZooKeeper() {
_classCallCheck(this, ZooKeeper);
};
var _Animal12 = function _Animal12() {
_classCallCheck(this, _Animal12);
};
var Bee = function (_Animal13) {
_inherits(Bee, _Animal13);
function Bee() {
_classCallCheck(this, Bee);
return _possibleConstructorReturn(this, (Bee.__proto__ || Object.getPrototypeOf(Bee)).apply(this, arguments));
}
return Bee;
}(_Animal12);
var Lion = function (_Animal14) {
_inherits(Lion, _Animal14);
function Lion() {
_classCallCheck(this, Lion);
return _possibleConstructorReturn(this, (Lion.__proto__ || Object.getPrototypeOf(Lion)).apply(this, arguments));
}
return Lion;
}(_Animal12);
createInstance(Lion).keeper.nametag; // typechecks! <- THIS CRASHES
// createInstance(Lion).keeper.hasMask; // error!
createInstance(Bee).keeper.hasMask; // typechecks!
}
这也是错误的堆栈:
Uncaught TypeError: Cannot read property 'nametag' of undefined
at Object.2../greet (main.ts:1451)
at s (_prelude.js:1)
at e (_prelude.js:1)
at _prelude.js:1
答案 0 :(得分:2)
该示例旨在显示键入行为,而不是完整的可运行程序。您遇到的问题是由于keeper
字段未在类中初始化而导致的。要让它运行,请尝试以下方法:
class Bee extends Animal {
keeper: BeeKeeper = new BeeKeeper();
}
class Lion extends Animal {
keeper: ZooKeeper = new ZooKeeper();
}