Edit: Fixed the code and added a TypeScript Playground example. The methods are correctly typed, you can verify this by the typing errors that are thrown, try and fix them ;). I copied over the very basic required interfaces from the angular definition file.
Edit #2: Here's the fixed version of the TypeScript Playground example above.
If I understand your question correctly, you're trying to define a return type for the service method stating it returns a promise whose result upon resolving will be a certain object?
In that case you're almost there, I've split up your two example methods in separate blocks, as they require a different approach.
On a general note, I removed the scope copying (self = this
) as you are using the fat arrow methods, which will automatically scope the method to the outer lexical scope. In short, there's no need to do the scope copy and in fact, in your example self doesn't always point to the service (as you're copying the scope inside of the method instead of outside of it).
Also, please note the definition of an Angular promise (truncated):
interface IDeferred<T> {
resolve(value?: T): void;
reject(reason?: any): void;
}
As such, typing an Angular Promise will only add a typing for the resolve case of the promise, not for the rejected case. Consequently, when calling your service, it will verify that the result in the success handler is of the type you have defined, but the type of the parameters in the error handler is of type any
.
topicTest
For this method to work you need to inject $q
into your service and then use it to create your own deferred
topicTest = (): IPromise<Foo> => { // return a promise which will result in a parameter of MyType upon resolving
var deferred = this.$q.defer<Foo>(); // Type the deferred to get better 'intellisense' support
if (this.abc = 99) {
deferred.resolve(new Foo());
}
if (this.abc = 88) {
deferred.reject("You can pass in whatever you like to the reject case");
}
return deferred.promise;
};
topicNewSubmit
The $http
already returns promises, so you only need to hook into these by attaching a then
callback and returning from that method to allow chaining other then
callabacks to it.
In that case the return type of your service method would be
angular.IPromise<() => any>
where you can replace
any
with a type you'd like. The return type of the
then
method would have to correspond to whatever type you chose for the generic placeholder in the return type of the service method.
topicNewSubmit = () : IPromise<Foo> => {
return this.$http({ url: this.url, method: "GET" }).then((response): Foo => {
return new Foo();
}, (error) => {
return "whatever you'd like, it does not have to correspond to Foo";
});
}
You could then use your service like
MyService.topicNewSubmit().then((data) => {
// data needs to be of type T, where T is the type you defined in the generic placeholder of IPromise<T>
}, (error: any) => {
// In the error case, the parameters are of type any
});