typescript import语句在运行时使用node.js计算为null

时间:2015-10-05 15:05:36

标签: typescript

我认为我正在进行错误的导入/导出,因为我没有得到打字稿编译器错误,但是尝试从另一个文件引用我的类ActivityType时出现运行时错误。

调用Experience.save()时出错:

import Activities = require('../models/Activities');
import ActivityType = Activities.ActivityType;

export class Experience extends BaseModel {

        static save(experience:Experience) {
            console.log(ActivityType.created) //this throws an error saying ActivityType is null
            experience.validate();
        }
}

models/Activities.ts

export class ActivityType {
    static created = 'created';
    static updated = 'updated';
    static commented = 'commented';
    static uploaded = 'uploaded';
    static joined = 'joined';
    static followed = 'followed';
    static chat = 'chat';
}

我尝试在module块中的Activities.ts中包装导出语句,例如。

module Activities {
  export class ActivityType {
    static created = 'created';
    static updated = 'updated';
    static commented = 'commented';
    static uploaded = 'uploaded';
    static joined = 'joined';
    static followed = 'followed';
    static chat = 'chat';
  }
}

然后在import语句中给了我Typescript错误。

1 个答案:

答案 0 :(得分:0)

我无法想出ActivityType为null的原因 - 通常必须明确设置。我甚至不确定如何根据您提供的代码来定义ActivityType。

有人猜测您可能会收到Cannot read property 'prototype' of undefined错误。如果是这种情况,您可能会追逐错误的内容,并且在使用extends关键字时实际上遇到了无序问题。如果你有一个基类和一个在同一个TypeScript文件中扩展它的类,那么基类必须是第一个。

此代码在编译为ES5和CommonJS时应该有效:

<强>模型/ Activities.ts

export class ActivityType {
    static created = 'created';
    // etc...
}

console.log("Activities loaded");

<强>代码/ test.ts

import Activities = require('../models/Activities');
// Using the import keyword doesn't change the emit, so this
// could just be var here.
import ActivityType = Activities.ActivityType;

class BaseModel {
    public thing = "hi";
}

export class Experience extends BaseModel {
    static save(experience:Experience) {
        console.log(ActivityType.created)
    }
}

const ex = new Experience();

Experience.save(ex);

如果您切换BaseModelExperience的声明顺序,它将适用于TypeScript,但在运行时会失败。

如果不是,请提供更多发出的代码。例如,BaseModel是如何/在哪里声明的?