未捕获的TypeError:UnitType不是构造函数

时间:2016-08-11 04:37:04

标签: javascript arrays typescript

我有一组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}';

}}

当我编译代码时,我正在

  

未捕获的TypeError:UnitType不是构造函数。

为什么我会收到此错误,如何解决? 我正在运行TypeScript 1.8.1。

1 个答案:

答案 0 :(得分: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';