cpowers
cpowers

Reputation: 393

TypeScript class that also acts as a function type

In attempting to implement angular's IHttpService, I am not sure how one would handle the following function.

interface IHttpService {
    <T>(config: IRequestConfig): IHttpPromise<T>;
}

class MyHttpService implements IHttpService
{
    // The following does not work
    <T>(config: IRequestConfig): IHttpPromise<T> 
    {
    }
}

Is this even possible?

Upvotes: 1

Views: 185

Answers (2)

Sly_cardinal
Sly_cardinal

Reputation: 12993

basarat is correct that you should use a regular function to implement the IHttpService interface.

For future reference, here is one of implementing that interface and using it in Angular:

interface IRequestConfig {}
interface IHttpPromise<T> {
    then: (resolve?: (value: T) => any, reject?) => IHttpPromise<T>;
}

interface IHttpService {
    <T>(config: IRequestConfig): IHttpPromise<T>;
}


function MyHttpService<T>(config: IRequestConfig): IHttpPromise<T>{
    // Define service behaviour here.
}


angular.module('MyModule')
    .service('MyHttpService', MyHttpService)
    .controller('MyController', function(MyHttpService: IHttpService){

        MyHttpService<MyType>({
            // Implement `IRequestConfig` here. 
        }).then(function(value){
            // Accces properties on `value`.
        });

    });

Upvotes: 0

basarat
basarat

Reputation: 276171

You cannot do that with a TypeScript class. You will need to fall back to using a simple function.

Not every interface you can define in TypeScript can be implemented using a TypeScript class. This is one of those cases.

Upvotes: 2

Related Questions