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

Uncaught TypeError: UnitType is not a constructor

本文关键字:UnitType 构造函数 TypeError      更新时间:2023-09-26

我有一个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不是构造函数

为什么我得到这个错误,我如何解决它?

我猜您由于不正确或缺少依赖关系而以错误顺序编译的问题。我不知道你是如何在文件之间分配你的东西,但下面的布局对我有用。当然,您可能需要根据您的环境相应地调整文件名和导入/引用。
希望能有所帮助

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';