cruzan cruzan - 4 months ago 110
TypeScript Question

Uncaught TypeError: UnitType is not a constructor

I have an array of UnitTypes defined as follows:

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'),
];


My UnitType class is defined as follows:

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

}}


When I compile the code I am getting Uncaught TypeError: UnitType is not a constructor. Why am I getting this error and how do I resolve it?
I am running TypeScript 1.8.1.

Answer

I guess you have issues with transpiling in the wrong order due to incorrect or missing dependencies. I am not aware of how you distributed your stuff between files but with the following layout it worked for me. Of course you may want to adjust the file names and imports / references accordingly for your environment.
Hope that helps

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