Gerard Wilkinson
Gerard Wilkinson

Reputation: 1541

Typescript transpiled Javascript does not include properties

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:

RfidData.ts

import { TimeModel } from "./Model";

export class RfidData extends TimeModel {
  DeviceId: string;
  Transponders: string[];
}

RfidData.js (compiled output)

"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.

.tsconfig (for reference)

{
  "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.

UPDATE -- Further Discussion

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

Answers (1)

jcalz
jcalz

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

Related Questions