0

In one TypeScript quickstart, there's part which casts Object to some class. See the full code below.

.map(res => <RegisteredApplicationModel> res.json()) 

How does this work? Is there some spec for that? Anything happening in the background or does it simply force the cast, leaving the responsibility that all fields are set and of the right type, on the author of that line?

@Injectable()
export class RegisteredApplicationService {
 private GET_APPLICATIONS_URL = "/registeredApplications/list";
 private REGISTER_APPLICATION_URL = "/registeredApplications/register";
 constructor (private _http: Http, private _constants: Constants) {}
 registerApplication(application:RegisteredApplicationModel) {
 let headers = new Headers();
 let options = new RequestOptions({ headers: headers });
 headers.append('Content-Type', 'application/json');
 headers.append('Accept', 'application/json');
 let body = JSON.stringify(application);
 return this._http.put(this._constants.REST_BASE + this.REGISTER_APPLICATION_URL, body, options)
 .map(res => <RegisteredApplicationModel> res.json())
 .catch(this.handleError);
 }
asked Jul 29, 2016 at 9:30

1 Answer 1

1

Yes there is a spec which is available here

In summary:

Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members

Classes

When comparing two objects of a class type, only members of the instance are compared. Static members and constructors do not affect compatibility.

So, when casting from <A>b, the compiler will check if (non optional) properties of A are not missing in the type of b.

If bis of type any, it can be cast to anything, as the name implies.

The latter is exactly the case the of the value of response.json() which type is any according to the documentation

So yes, the "responsibility that all fields are set and of the right type [is] on the author of that line"

answered Jul 29, 2016 at 9:55
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.