TypeError:对象原型只能是Object或为null:未定义

Ole*_*Ole 5 javascript node.js typescript ts-node

在下面的示例中,如果我导入,则会Entity得到帖子的主题错误(TypeError:对象原型可能只是一个Object或null:未定义),但是如果我将导入替换为实际的Entity声明,则代码可以正常运行。

Stackblitz演示在这里

这是Customer.ts在当我运行的代码产生错误的形式ts-node

索引

export { Customer } from "./Customer";
export { Entity } from "./Entity";
Run Code Online (Sandbox Code Playgroud)

客户

import { Entity } from "./index";

export class Customer extends Entity {
  sku: string;
  constructor(po: any) {
    super();
    this.sku = po.sku;
  }
}
Run Code Online (Sandbox Code Playgroud)

实体

export abstract class Entity {
  id?: string;
}    
Run Code Online (Sandbox Code Playgroud)

Run.ts(测试代码)

import {Customer} from "./";

let c = new Customer({
  name: "Bob"
});
console.log(c);
Run Code Online (Sandbox Code Playgroud)

如果我用这样Entity的声明替换导入:

export abstract class Entity {
  id?: string;
}    

export class Customer extends Entity {
  sku: string;
  constructor(po: any) {
    super();
    this.sku = po.sku;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后Run.ts记录以下内容:

Customer { sku: undefined }
Run Code Online (Sandbox Code Playgroud)

换句话说,它运行良好并且不会产生任何错误。有什么想法吗?

Mat*_*hen 7

我怀疑您的原始程序具有循环导入。 Run.ts进口index.ts,进口Customer.tsindex.ts再次进口。由于index.ts已经在加载过程中,并且它本身依赖于Customer.ts,因此import { Entity } from "./index";Just的Entityof index.ts(尚未设置)将绑定到Entityof Customer.ts,即使index.ts尚未完成加载,执行仍会继续。然后Entity在尝试扩展它时未定义。您可能会认为循环导入应该是错误的,或者JavaScript引擎应该使用其他可以正确处理您的情况的算法;我没有资格评论为什么选择当前设计。(其他人可以随意添加有关此信息。)

如您所见,更改Customer.ts./Entity直接从导入而不是./index中断循环,一切都按预期进行。另一个解决方案是将中的导入顺序颠倒index.ts