I am trying to figure out if a Typescript object is same as a Javascript object. I have a typescript variable into which I want to typecast result of JSON.parse which I suppose creates a javascript object from a json but I am unable to do it.
I have the following two classes
export class User {
constructor (public firstname:string,
public lastname:string,
public email:string,
public password:string=""){}
}
export class UserProfileAPI {
'external-profile': User;
constructor(externalProfile:User){
this['external-profile'] = externalProfile;
}
}
I have created a spec to test that an object created explicitly is same or similar to object created by json.parse but they don't seem to be.
fit('should test if Typescript object is same as Javascript object',()=>{
let user = new User('manu','chadha','[email protected]');
let dummyUserProfile:UserProfileAPI= new UserProfileAPI(user);
console.log('dummy profile is ',dummyUserProfile);
let dummyProfile2:UserProfileAPI = JSON.parse('{"external-profile":{"firstname":"manu","lastname":"chadha","email":"[email protected]"}}');
console.log('dummy profile 2 is ',dummyProfile2);
console.log('dummy profile1 == dummy profile 2',(dummyUserProfile == dummyProfile2));
console.log('dummy profile1 === dummy profile 2',(dummyUserProfile == dummyProfile2));
expect(dummyUserProfile).toEqual(dummyProfile2);
expect(dummyUserProfile).toBe(dummyProfile2);
});
In the above case, dummyUserProfile is printed as LOG: 'dummy profile is ', UserProfileAPI{external-profile: User{firstname: 'manu', lastname: 'chadha', email: '[email protected]', password: ''}} but dummyProfile2 is printed as LOG: 'dummy profile 2 is ', Object{external-profile: Object{firstname: 'manu', lastname: 'chadha', email: '[email protected]'}} and both the comparisons return false. Why?
trueunless you compare an object to itself.{} === {}will always give you false, for the same reason you're getting false. Object equality uses reference equality, not value equality.