简体   繁体   English

TypeScript-转换

[英]TypeScript - casting

In one TypeScript quickstart, there's part which casts Object to some class. 在一个TypeScript快速入门中,有一部分将Object强制转换为某个类。 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);
    }

Yes there is a spec which is available here 是的,有一个规范是可用在这里

In summary: 综上所述:

Type compatibility in TypeScript is based on structural subtyping. TypeScript中的类型兼容性基于结构子类型。 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 . 因此,从<A>b强制转换时,编译器将检查b的类型是否不缺少A (非可选)属性。

If b is of type any , it can be cast to anything, as the name implies. 如果b的类型为any ,顾名思义,可以将其强制转换为任何类型。

The latter is exactly the case the of the value of response.json() which type is any according to the documentation 后者恰好是response.json()值的情况,根据文档类型是any类型

So yes, the "responsibility that all fields are set and of the right type [is] on the author of that line" 所以是的,“所有字段的设置和正确类型的责任都在该行的作者身上”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM