我认为我正在进行错误的导入/导出,因为我没有得到打字稿编译器错误,但是尝试从另一个文件引用我的类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错误。
答案 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);
如果您切换BaseModel
和Experience
的声明顺序,它将适用于TypeScript,但在运行时会失败。
如果不是,请提供更多发出的代码。例如,BaseModel是如何/在哪里声明的?