TypeScript properties returning a promise - Get / Set accessors must have the same type

Why does TypeScript apply Get / Set accessors to the same type? Let me say that I want to have a property that returns a promise.

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

The Get and Install Accessor must be of the same type , this is an error message coming from TypeScript.

The fix will be to introduce accessors to any , but then we lose the benefits of static typing and can just write JS.

  get foo(): any { return this._fooDeferred.promise; } set foo(value: any) { this._fooDeferred.resolve(value); } 
+8
angularjs typescript
source share
1 answer

This sounds like a great opportunity to use a union type (TypeScript 1.4 or higher) - an example from 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); } } } 

Notes:

  • You will need to use type protection devices if you want to use a specific type from a union type
  • You may need to use type statements in some cases.

Type guard

The following is an example of type protection

 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 } 

Type approval

If necessary, you can approve the following types:

 var prom = <string> value; 
+8
source share

All Articles