user1662121 user1662121 - 1 year ago 107
TypeScript Question

TypeScript compiler produces incorrect output

I have the following typescript code labeled A below, in VS 2015 Update 3 but it produces code labeled B below. The problem is the source has fields but the output has none. Please help.


"use strict";
export class RoleViewModel {
public Id: number;
public Name: string;
public Description: string;
public IsEnabled: boolean;
public ResourceCustomizationId: number;


"use strict";
export class RoleViewModel {

Answer Source

Javascript doesn't know about fields declaration and TypeScript will remove all fields that are not assigned in your class or referenced by any method.

The workaround you have is to set a default value to those fields like this:

export class RoleViewModel {
    public Id: number = 0;
    public Name: string = "";
    public Description: string = "";
    public IsEnabled: boolean = false;
    public ResourceCustomizationId: number = 0;

And it will generate the following code:

export class RoleViewModel {
    constructor() {
        this.Id = 0;
        this.Name = "";
        this.Description = "";
        this.IsEnabled = false;
        this.ResourceCustomizationId = 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download