繁体   English   中英

TypeScript-转换

[英]TypeScript - casting

在一个TypeScript快速入门中,有一部分将Object强制转换为某个类。 请参阅下面的完整代码。

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

这是如何运作的? 有什么规格吗? 在后台发生的任何事情,还是只是强制转换,而将所有字段都设置为正确类型的责任留给了该行的作者?

@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);
    }

是的,有一个规范是可用在这里

综上所述:

TypeScript中的类型兼容性基于结构子类型。 结构化类型是一种仅基于其成员关联类型的方式

班级

比较两个类类型的对象时,仅比较实例的成员。 静态成员和构造函数不影响兼容性。

因此,从<A>b强制转换时,编译器将检查b的类型是否不缺少A (非可选)属性。

如果b的类型为any ,顾名思义,可以将其强制转换为任何类型。

后者恰好是response.json()值的情况,根据文档类型是any类型

所以是的,“所有字段的设置和正确类型的责任都在该行的作者身上”

暂无
暂无

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

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