Vue js , TypeScript class object initial field values
Recently ran into some issues (Colleague of mine noticed it) working with VueJs (maybe its the same in Angular, but can’t remember).
The issue is if you have a class implementation as below
export interface IAsset { BuildingAssetId: number; Label: string; } export class Asset implements IAsset { public BuildingAssetId: number; public Label: string; constructor() { } }
And if you initialise a new object like below
asset: IAsset = new Asset();
Properties won’t get default values, for example in C# if you do this, string fields will have an empty string (”), bool will have false, so on…
But it’s not the case with TypeScipt/Vue/Js (well, not sure – someone please enlighten me!!!!)
You either need to set the initial values in the constructor() liek below
export class Asset implements IAsset { public BuildingAssetId: number; public Label: string; constructor() { this.BuildingAssetId = 0; this.Label= ""; } }
Or even better
export class Asset implements IAsset { public BuildingAssetId: number = 0; public Label: string = ""; constructor() { } }
Alternatively, you can do it like this too.
export class Asset implements IAsset { constructor( public BuildingAssetId: number, public Label: string) { } }
and you can init values like new Asset(0);
Sweet