gpt4 book ai didi

javascript - TS 文档提供的小型已编译 Typescript 代码崩溃

转载 作者:行者123 更新时间:2023-12-01 02:25:53 27 4
gpt4 key购买 nike

我一直在关注 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

最佳答案

该示例旨在显示键入行为,而不是完整的可运行程序。您遇到的问题是由于 keeper 字段未在类中初始化而引起的。要让它运行,请尝试以下操作:

class Bee extends Animal {
keeper: BeeKeeper = new BeeKeeper();
}
class Lion extends Animal {
keeper: ZooKeeper = new ZooKeeper();
}

关于javascript - TS 文档提供的小型已编译 Typescript 代码崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48808825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com