Typescript - 从泛型方法返回一个promise

时间:2018-04-04 18:21:12

标签: typescript es6-promise

我有一个问题,我试图从我的一种方法中返回一个承诺,但是,它抱怨类型'不可分配'。见下面的例子:

interface Test {
    prop1: string
}

interface Interface {
    oneMethod<T>(): Promise<T>;
}

class implementation implements Interface {
    oneMethod<Test>(): Promise<Test> {
        return Promise.resolve({
            prop1: 'test'
        });
    }
}

我收到错误:

error TS2322: Type 'Promise<{ prop1: string; }>' is not assignable to type 'Promise<Test>'.
  Type '{ prop1: string; }' is not assignable to type 'Test'.

我尝试添加&#39;作为测试&#39;返回对象然后返回问题&#39;无法转换为类型测试&#39;

令人讨厌的是,这很好用:

class anotherImp {

    oneMethod(): Promise<Test> {
        return Promise.resolve({
            prop1: 'test'
        });
    }
}

但这并没有实现我的通用接口。如果我从界面中的oneMethod签名中删除T,那么我得到一个关于Promise不知道T的错误(找不到名字&#39; T&#39;)。从两者中删除都会给我一个错误,即Promise必须实现一个类型(Generic type&#39; Promise&#39;需要1个类型的参数。)

任何想法都非常感激。

由于 伊恩

1 个答案:

答案 0 :(得分:1)

以这种方式尝试:

interface Test {
    prop1: string
}

interface Interface<T> {
    oneMethod(): Promise<T>;
}

class implementation implements Interface<Test> {
    oneMethod(): Promise<Test> {
        return Promise.resolve({
            prop1: 'test'
        });
    }
}

当您将方法/函数定义为method<Type>(): Type时,您不会返回现有类型Type(如果有)。您告诉TypeScript该方法是通用的,并将返回您通过type参数指定的任何类型。

通常,您不会在非泛型接口中使用泛型方法。最好将接口定义为通用接口,因此该方法取决于接口的类型。否则,您可以将类型定义为泛型函数,忘记接口。

相关问题