I've JSON
string
const json = '{ "first_name": "John", "last_name": "Doe"}';
and a class User
class User {
constructor(
public first_name: string,
public last_name: string
) {
}
public getFullName = (): string => {
return this.first_name + ' ' + this.last_name;
};
}
and when I try this
const user: User = JSON.parse(json);
console.log(user.first_name); // Works, prints "John"
console.log(user.last_name); // Works, prints "Doe"
console.log(user.getFullName()); //Error: TypeError: user.getFullName is not a function
I know the error happened, because JSON.parse
simply matched the User
type but not methods in it.
So to fix this, I wrote a fromJSON
static method in User
class to parse manually,
public static fromJSON = (json: string): User => {
const jsonObject = JSON.parse(json);
return new User(
jsonObject.first_name,
jsonObject.last_name
);
};
So these are my questions
- Is this a perfect solution ?
- Is there any better solution than this ?
- Is there any built-in solution for this in
TypeScript
?