In spite of what I heard in this talk about how it was getting taken away it still seems pretty rampant and hard to police. Look how easy it is to sidestep a constructor on a class.
class Person {
public Age: number;
public BirthDate: Date;
public IsMale: boolean;
public Name: string;
constructor(birthDate: Date) {
this.BirthDate = birthDate;
this.Age = new Date().getFullYear() - birthDate.getFullYear();
}
}
let Alice: Person = new Person(new Date(1969, 1, 1));
console.log(Alice.Age);
console.log(Alice.BirthDate);
let Bob: Person = <Person>{};
console.log(Bob.Age);
console.log(Bob.BirthDate);
This code puts the following to the console:
- 49
- Sat Feb 01 1969 00:00:00 GMT-0600 (Central Standard Time)
- undefined
- undefined
I noticed this trick on page 208 of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis. I would consider {} kind of like object in C#. This really feels like casting a parent to a child.
No comments:
Post a Comment