Wudong
Wudong

Reputation: 2360

How typescript object cast work

I have defined a class as follow:

class Foo {
  p1: string;
  p2: string;
  a_method(): string{
    return p1+p2;
  }
};

And I have a service to return JSON object which corresponding to the Foo.

var foo: Foo= <Foo> restService.getOne(1);

So the above code work ok, but I'm wondering if the following code will work:

foo.a_method();

My understanding is that when the JSON is converted to a javascript, it shouldn't have any method attached to it. Unless typescript does something when casting, the code above shouldn't be working.

Also I'm wondering in javascript in general, how should I implement this cast.

Upvotes: 2

Views: 853

Answers (2)

basarat
basarat

Reputation: 275867

As you suspect it will not work. TypeScript doesn't do type casting, it does type assertion i.e you are telling the compiler this is what I say this object is, forget what you inferred before. There is no change in the generated javascript when you use type assertion.

As for recommended approach : create a typescript class that accepts the DTO as a constructor argument and uses the DTO to populate itself.

Upvotes: 6

Akash Yadav
Akash Yadav

Reputation: 2421

Ideally your service wouldn't /shouldn't return any object that has behaviors usually service json objects are meant for data objects.

Provided that you should have another object to contain behavior and data object will contain only the data members which will be returned from service .

To add to that there is also a return type jsonp which itself is a function returned from the service , you might be interested in that if that's the need

Upvotes: 0

Related Questions