Reputation: 9806
I have a animal class and interface,
interface IAnimal {
name: string;
}
class Animal {
// Fields
_data: IAnimal;
// Constructor
constructor(
data: IAnimal
) {
console.log('name: ' + data.name);
}
// Propperties
get name() {
return this._data.name
}
set name(value: string) {
if (value.length < 1) {
alert("No name");
} else {
this._data.name = value
}
}
}
let lionJon = new Animal({name: ''});
As you can see I'm creating a new object but with an empty name string. I would expect the set name
to throw an alert since the value of name is less then 1 character long.
Instead it skips the whole get and set and goes straight to the contructor, bypassing the check.
Upvotes: 0
Views: 53
Reputation: 3678
It appears that you're trying to use the C# "property initializer" syntax with your Animal type. However, what you're actually doing is passing an object into the constructor and then ONLY printing the value of the name property. If you were to follow that console.log statement with an assignment to this.name, you would see the runtime error:
this._data = new Animal(); // Otherwise we'll get a reference error
console.log('name: ' + data.name);
this.name = data.name;
Now, that should resolve your original issue, but I do see another conceptual issue with your code: you're defining an IAnimal interface, but you're containing that interface in your Animal class instead of implementing it. While this isn't technically a problem, you should be asking yourself whether Animal is an IAnimal or whether it has an IAnimal. In this case, I suspect you intend the former, which would make your code look like:
interface IAnimal {
name: string;
}
class Animal implements IAnimal {
// Note that we now have a member to contain the
// backing value for the 'name' property here instead
// of the original IAnimal type.
private _name : string;
// Constructor
constructor(
data: IAnimal
) {
console.log('name: ' + data.name);
this.name = data.name;
}
// Properties
get name() {
return this._name
}
set name(value: string) {
if (value.length < 1) {
alert("No name");
} else {
this._name = value;
}
}
}
let lionJon = new Animal({name: ''});
Upvotes: 2
Reputation: 164317
I've decided to write an answer, not in order to answer your question but to point out an issue you might get yourself into.
First of, to answer what I did in my comment, you need to call the setter yourself, so you ctor should look something like this:
constructor(data: IAnimal) {
this.name = data.name;
}
Another problem you have here is that you don't assign a value to the _data
member, so it should look like:
constructor(data: IAnimal) {
this._data = {};
this.name = data.name;
}
And then you'll be good, but beware of doing this:
this._data = data;
Because then you might find yourself having a reference for the same object in different instance of Animal
.
Upvotes: 1