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);
}
1 Answer 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"