Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

How to get the proper class during a cast from JSON in typescript?

I have a very simple class

export class Foo {

    name: string;

    index: number;

    toFullString(): string {
        return `${this.name} | ${this.index}`;
    }
}

I get elements of this class from a server and cast json to this class:

.map(response => response.json() as Foo)

Now what happens is that after I call toFullString() method it fails since this is not the "real" Foo object as it would be in say C#.

So what is the proper way of achieving real Foo object, preferably without the need of writing your own constructors and so on.

The type safety in TypeScript is a joke sometimes really.

Upvotes: 1

Views: 463

Answers (2)

silentsod
silentsod

Reputation: 8335

Either you're going to have to write your own constructor or you'll have to take your returned obejcts and append the function (technically legal JS) with for(let obj of responseObjects) { obj['toFullString'] = function ... }. One you don't want, and the other is a little sketchy.

The constructor method you have already seen but I'll repeat here:

constructor(public name, public index) {
    this.name = name;
    this.index = index;
}

You could also do it in the map which is the same thing.

masterFoo: Foo = new Foo();

mapFoo(responseObject: any) {
    <...>
    responseObject['toFullString'] = masterFoo.toFullString;
    <...>
  }

The auto mapping works for data objects only, and it's a limitation due to JS being the underlying language of it all.

Here's a plunker demonstrating appending the function to a Plain Old JavaScript Object: http://plnkr.co/edit/BBOthl0rzjfEq3UjD68I?p=preview

Upvotes: 1

Ploppy
Ploppy

Reputation: 15353

You could create the Object and give it the JSON values.

.map(res => this.onResponse(res))

-

function onResponse(res:any){
    this.foo = new Foo();
    this.foo.name = res['name'];
    ...
}

Or give the JSON values to the constructor of Foo

this.foo = new Foo(res['name'], ...);

Upvotes: 1

Related Questions