下面如果我导入 Entity
我得到帖子的主题错误(TypeError:对象原型可能只是一个对象或 null:未定义),但是如果我用实际的 Entity
声明替换导入代码运行良好。
这是 Customer.ts
在我运行代码时产生错误的形式 ts-node
:
索引.ts
export { Customer } from "./Customer";
export { Entity } from "./Entity";
客户.ts
import { Entity } from "./index";
export class Customer extends Entity {
sku: string;
constructor(po: any) {
super();
this.sku = po.sku;
}
}
实体.ts
export abstract class Entity {
id?: string;
}
Run.ts(测试代码)
import {Customer} from "./";
let c = new Customer({
name: "Bob"
});
console.log(c);
如果我用这样的声明替换 Entity
导入:
export abstract class Entity {
id?: string;
}
export class Customer extends Entity {
sku: string;
constructor(po: any) {
super();
this.sku = po.sku;
}
}
然后 Run.ts
记录这个:
Customer { sku: undefined }
换句话说,它运行良好并且不会产生任何错误。想法?
原文由 Ole 发布,翻译遵循 CC BY-SA 4.0 许可协议
正如我所怀疑的,您的原始程序具有循环导入。
Customer.ts
Run.ts
进口index.ts
index.ts
Sinceindex.ts
is already in the process of loading and itself depends onCustomer.ts
, theimport { Entity } from "./index";
just binds theEntity
ofindex.ts
(尚未设置)到Entity
的Customer.ts
,即使index.ts
加载未完成,执行也会继续。然后Entity
在您尝试扩展它时未定义。您可能会争辩说循环导入应该是一个错误,或者 JavaScript 引擎应该使用其他一些算法来正确处理您的场景;我没有资格评论为什么选择当前设计。 (其他人可以随意添加有关此的信息。)如您所见,将
Customer.ts
直接从./Entity
导入,而不是./index
导入,打破了循环,一切都按预期进行。另一种解决方案是颠倒index.ts
中的导入顺序。