Why is it necessary for TypeScript to require Get/Set accessors to have the same type? For example, if we want 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);
}
}
}
'Get' and 'Set' accessor must have the same type is the error message that TypeScript will display.
To resolve this issue, one could simply change the accessors to type any. However, this would eliminate the benefits of static typing, essentially converting the code back to JavaScript.
get foo(): any {
return this._fooDeferred.promise;
}
set foo(value: any) {
this._fooDeferred.resolve(value);
}