In my TypeScript app, I am utilizing API calls to retrieve objects. Specifically, I have a TypeScript User
Object structured like this:
export class User {
id : number;
name : string;
email : string;
}
Upon making the API call, the data returned looks like this:
{
"id" : 3,
"name" : "Jonn",
"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8d2d7d0d6f8ddc0d9d5c8d4dd96dbd7d5">[email protected]</a>"
}
I want to convert this JSON data into a User
. Initially, I attempted this method:
let user : User = <User> myJson;
While I can successfully access properties of the user like user.name
, the issue arises when trying to access methods within the User
class. For example, if the User
class contains a method such as:
getUppercaseName() : string {
return this.name.toUpperCase();
}
The behavior observed is that while user.name
returns John
, attempting user.getUppercaseName()
results in undefined
.
What could be causing this discrepancy? And what would be the best approach to overcome this challenge?