Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angularjs – 返回promise的TypeScript属性 – Get / Set访问器必须具有相同的类型大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么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;

大佬总结

以上是大佬教程为你收集整理的angularjs – 返回promise的TypeScript属性 – Get / Set访问器必须具有相同的类型全部内容,希望文章能够帮你解决angularjs – 返回promise的TypeScript属性 – Get / Set访问器必须具有相同的类型所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: