Typescript - set default value for class members
The reason you're seeing overwriting properties is due to type erasure in TypeScript. TypeScript has no idea what types of objects are assigned to its variables during runtime. This would seem somewhat strange to you if you're coming not from a java / c# background.
Because in the end , it's just JavaScript. And JavaScript doesn't enforce strict type checking.
In order to ensure that your profile objects always have an age property, you could create your own objects then copy over the values you get from the response. This is the usual approach when it comes to wire format to domain object mapping.
To do this first create your domain model, a Profile class with a default age property in this case.
export class Profile {
constructor(
public name: string,
public email: string,
public age: number = 0) { }
}
Then map your response to the domain model.
this.resultsManagerService.getResults(this.config.request.action, this.pagingAndSorting, this.args).subscribe(
results => {
let res = (results as Profile[]).map((profile) => new Profile(profile.name, profile.email, profile.age));
this.results = this.results.concat(res);
});
Yes, easily, and you don't need to add a class constructor.
export class Profile extends ServerData {
name: string;
email: string;
age: number = 0;
}
The ability to define default values is one of the main things that differentiates a class
from an interface
.
For this to work you need to call new Profile()
somewhere in your code, otherwise a class instance won't be created and you won't have defaults set, because the above TypeScript will compile to the following JavaScript:
var Profile = /** @class */ (function () {
function Profile() {
this.age = 0;
}
return Profile;
}());
So just using it for type assertion at compile-time isn't sufficient to set a default at run-time.
See it in action in the TypeScript Playground.
You don't need to do much aside from use a constructor.
export class Profile extends ServerData {
name: string;
email: string;
age: number;
constructor(name: string = '', email: string = '', age: number = null) {
this.name = name;
this.email = email;
this.age = age;
}
}
This will create default params for things you are missing.