我有一个 UnitType
实例数组,定义如下:
export type MeasurementType = 'weight' | 'length' | 'temperature' | 'pressure';
export type UnitKeyType =
'kg' | 'lb'
| 'cm' | 'm' | 'ft' | 'in';
export var UNIT_TYPES: Array<UnitType> = [
new UnitType('kg', 'kilogram', 'weight'),
new UnitType('lb', 'pound', 'weight'),
new UnitType('cm', 'centimeter', 'length'),
new UnitType('m', 'meter', 'length'),
new UnitType('ft', 'feet', 'length'),
new UnitType('in', 'inch', 'length'),
];
我的 UnitType
类定义如下:
export class UnitType {
constructor(private _code: UnitKeyType, private _name: string,
private _measurementType: MeasurementType) {
}
get code(): string {
return this._code;
}
get name(): string {
return this._name;
}
get measurementType(): MeasurementType {
return this._measurementType;
}
static fromKey(key: UnitKeyType): UnitType {
let unit = UNIT_TYPES.filter(unit => unit.code === key)[0];
return unit;
}
toString(): string {
return this.toFormatString();
}
toFormatString(): string {
return '${this.measurementType}: ${this.name}';
}}
当我编译我得到的代码时
Uncaught TypeError: UnitType is not a constructor.
为什么会出现此错误以及如何解决? 我正在运行 TypeScript 1.8.1。
最佳答案
我猜您遇到了由于不正确或缺少依赖项而导致以错误的顺序进行转译的问题。我不知道你是如何在文件之间分配你的东西的,但下面的布局对我有用。当然,您可能希望根据您的环境相应地调整文件名和导入/引用。
希望有帮助
UnitType.ts
import {MeasurementType, UnitKeyType} from './Util.ts'
export class UnitType {
constructor(private _code: UnitKeyType, private _name: string,
private _measurementType: MeasurementType) {
}
get code(): string {
return this._code;
}
get name(): string {
return this._name;
}
get measurementType(): MeasurementType {
return this._measurementType;
}
static fromKey(key: UnitKeyType): UnitType {
let unit = UNIT_TYPES.filter(unit => unit.code === key)[0];
return unit;
}
toString(): string {
return this.toFormatString();
}
toFormatString(): string {
return '${this.measurementType}: ${this.name}';
}}
export var UNIT_TYPES: Array<UnitType> = [
new UnitType('kg', 'kilogram', 'weight'),
new UnitType('lb', 'pound', 'weight'),
new UnitType('cm', 'centimeter', 'length'),
new UnitType('m', 'meter', 'length'),
new UnitType('ft', 'feet', 'length'),
new UnitType('in', 'inch', 'length'),
];
Util.ts
export type MeasurementType = 'weight' | 'length' | 'temperature' | 'pressure';
export type UnitKeyType =
'kg' | 'lb'
| 'cm' | 'm' | 'ft' | 'in';
关于javascript - 未捕获的类型错误 : UnitType is not a constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887348/