TypeScript class 也充当函数类型

TypeScript class that also acts as a function type

在尝试实现 angular 的 IHttpService 时,我不确定如何处理以下函数。

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

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

这可能吗?

你不能用 TypeScript class 做到这一点。您将需要回退到使用一个简单的函数。

并非您可以在 TypeScript 中定义的每个接口都可以使用 TypeScript class 来实现。这是其中一个案例。

basarat 是正确的,您应该使用常规函数来实现 IHttpService 接口。

为了将来参考,下面是实现该接口并在 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`.
        });

    });