【问题标题】:TypeScript Error Object prototype may only be an Object or null: undefinedTypeScript 错误对象原型可能只是一个对象或 null:未定义
【发布时间】:2018-08-11 20:19:17
【问题描述】:

嘿,我刚开始使用 TypeScript,我尝试将 javascript 复制到 TypeScript 并将内容更改为更加面向对象。 现在我正在尝试使用 cmd 和 ns-node 命令启动它。

private username:string;
           ^
TypeError: Object prototype may only be an Object or null: undefined

这个错误没有任何意义,所以我用谷歌搜索了一下,发现问题可能是项目的导入。我已经在不同的网站上尝试了每一个灵魂,但它们没有帮助。

所以我的代码:

import { Entity } from './Entity';
import { Bullet } from './Bullet';

import * as fs from "fs";
export class Player extends Entity{

private username:string;
protected pressingRight:boolean ;
protected pressingLeft:boolean ;
...
}

那么可能是什么问题?感谢您的帮助

编辑:

    import {Point} from "./Point";
    import {Bullet} from "./Bullet";
import {Player} from "./Player";
export class Entity{

protected x:number;
protected y:number;
protected spdX:number = 0;
protected spdY:number = 0;
protected id:number;
protected map:string;


protected static initPack = {player:[],bullet:[]};
protected static removePack = {player:[],bullet:[]};

 constructor(x:number,y:number,id:number,map:string){
    this.x = x;
    this.y=y;
    this.id=id;
    this.map=map;
 }
...}

还有 Bullet.ts:

    import {Entity} from './Entity';
import {Player} from './Player';
export class Bullet extends Entity{

private angle:number;
private parentID:number;
private timer:number = 0;
private toRemove:boolean=false;

public static list={};

constructor(x:number,y:number,map:string,parentId:number,angle:number,id:number){
    super(x,y,id,map);
    this.angle = angle;
    this.spdX= Math.cos(angle/180*Math.PI) * 10;
    this.spdY= Math.sin(angle/180*Math.PI) * 10;
    this.parentID = parentId;

    Bullet.list[this.id] = self;
    Bullet.initPack.bullet.push(this.getInitPack());
}

【问题讨论】:

  • 我猜错误是指Player 的超类Entity。尝试在export class Player 上方添加console.log(Entity); 并确保已定义。
  • @MattMcCutchen 哇,你的权利 ^^ 你,我该如何解决这个问题?它们位于同一文件夹中,因此它应该与 ./ 前缀一起使用
  • 您能否将Entity.ts 的相关部分添加到问题中,以便我可以尝试重现问题?
  • @MattMcCutchen 好的,我已经使用 Entity 和 Bullet 类编辑了帖子

标签: javascript typescript import


【解决方案1】:

您有循环导入。根据您从哪个文件开始,当 ts-node 导入已在加载过程中的文件时,即使导入的文件尚未完成加载,它也会继续进行该导入。这就是您可以通过import { Entity } from './Entity';Entity 仍然可以未定义的方式。

如果在加载文件时Entity.ts 不需要访问Player 类,请尝试将import { Player } from './Player'; 行移动到Entity.ts 的底部。

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 2020-09-27
    • 2020-01-08
    • 2018-08-06
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多