我有一个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'),
];

myUnitType类定义如下:
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}';

}}

当我编译得到的代码时
未捕获类型错误:UnitType不是构造函数。
为什么我会得到这个错误,我如何解决它?
我正在运行TypeScript1.8.1。

最佳答案

我猜你有问题,以错误的顺序传输由于不正确或丢失的依赖关系。我不知道你是如何在文件之间分发你的东西的,但以下的布局对我有效。当然,您可能需要根据您的环境相应地调整文件名和导入/引用。
希望能帮上忙
单位类型.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'),
];

实用工具
export type MeasurementType = 'weight' | 'length' | 'temperature' | 'pressure';
export type UnitKeyType =
    'kg' | 'lb'
    | 'cm' | 'm' | 'ft' | 'in';

09-19 19:45