I've been following Typescript's Handbook but script crashes on the code example that you can find here:
https://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties
Can anyone help me resolving this issue?
{
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!
}
This is the code block compiled in 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!
}
And this is also the error's stack:
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
Aucun commentaire:
Enregistrer un commentaire