Reputation: 1541
My transpiled Javascript for my client side models do not include the properties from the Typescript files.
These properties are never directly set as they are parsed and mapped from JSON so I thought perhaps the compiler was being clever and optimising the code to remove unused properties but I don't see any options to turn such behaviour off so perhaps something else.
One of my models as an example:
import { TimeModel } from "./Model";
export class RfidData extends TimeModel {
DeviceId: string;
Transponders: string[];
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Model_1 = require("./Model");
class RfidData extends Model_1.TimeModel {
}
exports.RfidData = RfidData;
//# sourceMappingURL=RfidData.js.map
As you can see the two properties DeviceId
and Transponders
don't make it into the transpiled output.
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"moduleResolution": "node",
"module": "commonjs",
"target": "es6",
"outDir": "Client/js/"
},
"exclude": [
"node_modules",
"wwwroot"
]
}
Any help would be greatly appreciated.
After a good discussion there is another issue here which is that types are stripped after being transpiled, type erasure as jcalz points out. So mapping JSON through with an interface or setting the properties manually doesn't solve the issue if you have typed properties. For instance a Date
is left as any in an underlying class so you cannot access any relevant properties, its left as a string on the JS.
Is there anyway to maintain types in ES6 transpiled from TypeScript? Otherwise this question was rather academic. :(
Upvotes: 2
Views: 1146
Reputation: 328598
TypeScript erases all type information when it transpiles to JavaScript. In your case, the property declarations aren't setting any values, so they are erased too. I'm not sure why you want to see them at runtime if you aren't setting their values, but you probably have your reasons.
If you really want to see properties in the JavaScript, then you can initialize them to values:
export class RfidData extends TimeModel {
DeviceId: string = "";
Transponders: string[] = [];
}
transpiles to
class RfidData extends Model_1.TimeModel {
constructor() {
this.DeviceId = "";
this.Transponders = [];
}
}
If you can't think of reasonable initial values, you can set them to undefined
or void 0
(and if you have --strictNullChecks
on you will have to use undefined!
or the like).
Hope that helps; good luck!
Upvotes: 4