Difference between Javascript object and Typescript object

0 votes

I am trying to figure out if a Typescript object is the same as a Javascript object. I have a typescript variable into which I want to typecast the 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 the same or similar to an 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','test@test.com');
    let dummyUserProfile:UserProfileAPI= new UserProfileAPI(user);
    console.log('dummy profile is ',dummyUserProfile);
    let dummyProfile2:UserProfileAPI = JSON.parse('{"external-profile":{"firstname":"manu","lastname":"chadha","email":"test@test.com"}}');
    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: 'test@test.com', password: ''}} but dummyProfile2 is printed as LOG: 'dummy profile 2 is ', Object{external-profile: Object{firstname: 'manu', lastname: 'chadha', email: 'test@test.com'}} and both the comparisons return false. Why?

Aug 1, 2022 in TypeSript by Elton
• 400 points

edited Mar 4 14 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP