There is a difference in the type you are creating. In the first case you are createing an instance of Person
, in the second you are creating an object that has the same shape as Person.
There are differences between the two, for example insanceof
behaves differently.
var P1 = new Person("John", "Smith");
var P2 : Person = {FirstName:"John", LastName:"Smith"};
console.log(P1 instanceof Person) // true
console.log(P2 instanceof Person) // false
Also if your class has methods, you would need to specify them when initializing with an object literal:
class Person {
FirstName: string = "";
LastName: string = "";
constructor(FN: string, LN: string) {
this.FirstName = FN;
this.LastName = LN;
}
fullName() { return this.LastName + this.FirstName; }
}
var P2: Person = { FirstName: "John", LastName: "Smith" }; // error fullName missing
var P3: Person = { FirstName: "John", LastName: "Smith", fullName: Person.prototype.fullName }; // ok
And if the class has privates you can't build a compatible object literal:
class Person {
FirstName: string = "";
LastName: string = "";
constructor(FN: string, LN: string) {
this.FirstName = FN;
this.LastName = LN;
}
private fullName;
}
var P2: Person = { FirstName: "John", LastName: "Smith" }; // error Property 'fullName' is missing in type
var P3: Person = { FirstName: "John", LastName: "Smith", fullName: ""}; // Property 'fullName' is private in type 'Person' but not in type