angularjs – 返回promise的TypeScript属性 – Get / Set访问器
发布时间:2020-12-17 07:25:51 所属栏目:安全 来源:网络整理
导读:为什么TypeScript强制Get / Set访问器具有相同的类型? 假设我想拥有一个返回承诺的属性. module App { export interface MyInterface { foo: ng.IPromiseIStuff; } export interface IStuff { bar: string; baz: number; } class MyClass implements MyInte
为什么TypeScript强制Get / Set访问器具有相同的类型?
假设我想拥有一个返回承诺的属性. module App { export interface MyInterface { foo: ng.IPromise<IStuff>; } export interface IStuff { bar: string; baz: number; } class MyClass implements MyInterface { private _fooDeferred: ng.IDeferred<IStuff>; constructor(private $q: ng.IQService) { this._fooDeferred = this.$q.defer(); } get foo(): ng.IPromise<IStuff> { return this._fooDeferred.promise; } set foo(value: IStuff) { this._fooDeferred.resolve(value); } } } “获取”和“设置”访问器必须具有相同的类型才会是来自TypeScript的错误消息. 修复方法是键入任何访问器,但后来我们失去了静态类型的优点,并且可能只是编写JS. get foo(): any { return this._fooDeferred.promise; } set foo(value: any) { this._fooDeferred.resolve(value); }
这听起来像是使用联合类型(TypeScript 1.4或更高版本)的绝佳机会 – 从
this blog post获取的示例:
type StringPromise = string | ng.IPromise<string>; module App { export interface MyInterface { foo: ng.IPromise<string>; } class MyClass implements MyInterface { private _fooDeferred: ng.IDeferred<string>; constructor(private $q: ng.IQService) { this._fooDeferred = this.$q.defer(); } get foo(): StringPromise { return this._fooDeferred.promise; } set foo(value: StringPromise) { this._fooDeferred.resolve(value); } } } 笔记: >如果要使用联合类型中的特定类型,则需要使用类型保护 键入Guard 这是一个类型后卫的例子 if (typeof value === 'string') { // the type of value inside this if statement is // string,rather than StringPromise } else { // the type of value inside this else statement is // ng.IPromise<string>,rather than StringPromise } 键入断言 如果需要,您可以断言这样的类型: var prom = <string> value; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |