javascript - 类型错误 : Object prototype may only be an Object or null: undefined

标签 javascript node.js typescript ts-node

下面,如果我导入 Entity,我会得到帖子的主题错误(类型错误:对象原型(prototype)可能只是一个对象或 null:未定义),但是如果我用实际的 Entity 替换导入 声明代码运行正常。

Stackblitz demo here .

这是 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) Entityindex.ts (尚未设置)到 EntityCustomer.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/

相关文章:

javascript - 在WebSQL服务器中存储JSON数据

javascript - 用这个字符: "\"分割

javascript - HTML Canvas 上的分层和轮廓

javascript - 对于 node.js 中的路径中的值 "[object Object]",强制转换为未定义失败

node.js - Windows 上的 MongoDB 副本集面临一些基本问题

javascript - 多个 Facebook 像素,像素助手中的错误

html - 类型 'filter' 上不存在属性 'Object'。尝试过滤响应时

javascript - 在 Angular 4 中使用依赖注入(inject)扩展类

node.js - Nestjs:如何使用nest/cli 从nestjs monorepo 中删除特定应用程序

node.js - 验证 hapi server.log 正在使用预期消息进行调用