如何定义这种类型

时间:2020-07-30 08:54:53

标签: typescript

我有一个定义如下的通用函数:

function foo<T extends Record<string, unknown>>(arg1: string, arg2: string): Promise<T> {
  // Could get data from network
  return Promise.resolve({ arg1, arg2 } as any as T);
}

我想生成一系列属于的通用函数

const foo1 = foo.bind(null, 'a');
const foo2 = foo.bind(null, 'b');
// ...

我的问题是:如何为foo1,foo2等添加显式类型声明?

我尝试如下添加类型声明:

type B = <T extends Record<string, unknown>>(arg2: string) => Promise<T>;

const foo1: B = foo.bind(null, 'a');

它可以在一个打字稿项目中工作,但是在我的新打字稿项目中却行不通。我收到类似以下的构建错误:

TS2322: Type '(arg2: string) => Promise<Record<string, unknown>>' is not assignable to type 'B'.
  Type 'Promise<Record<string, unknown>>' is not assignable to type 'Promise<T>'.
    Type 'Record<string, unknown>' is not assignable to type 'T'.
      'Record<string, unknown>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record<string, unknown>'.

谢谢

1 个答案:

答案 0 :(得分:1)

现在我使用以下解决方法来解决此问题。

const foo1 = foo.bind(null, 'a') as any as B;
相关问题