下面,如果我导入 Entity
,我会得到帖子的主题错误(类型错误:对象原型(prototype)可能只是一个对象或 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 }
换句话说,它运行良好并且不会产生任何错误。想法?
最佳答案
正如我所怀疑的,您的原始程序具有循环导入。 Run.ts
进口index.ts
, 进口Customer.ts
, 进口index.ts
再次。自 index.ts
已经在加载过程中,它本身依赖于 Customer.ts
, import { Entity } from "./index";
只绑定(bind) Entity
的 index.ts
(尚未设置)到 Entity
的 Customer.ts
, 即使 index.ts
执行也会继续没有完成加载。那么Entity
在您尝试扩展它时未定义。您可能会争辩说循环导入应该是一个错误,或者 JavaScript 引擎应该使用其他一些算法来正确处理您的场景;我没有资格评论为什么选择当前设计。 (其他人可以随意添加这方面的信息。)
如您所见,更改 Customer.ts
从 ./Entity
导入直接代替 ./index
打破循环,一切都按预期进行。另一种解决方案是颠倒 index.ts
中的进口顺序.
关于javascript - 类型错误 : Object prototype may only be an Object or null: undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53122751/