来自类型数组的 Typescript 泛型类型约束

Typescript generic type constraint from array of types

我有一个类型数组声明为

const APIS = [NewsApi, CommentsApi, FileApi];

我想要一个方法来接受来自 APIS 数组的其中一种类型,如下所示:

myMethod<T extends anyof APIS>(apiType: T): T {
    const api = new apiType(); //pseudo code, does not work off course
    // some common configuration code
    return api;
} 

。我无法执行 myMethod<T extends NewsApi|CommentsApi>(): T,因为 APIS 数组是自动生成的。这可以用打字稿吗?

更新:

Aleksey 的解决方案非常适合传递输入。但是,return类型无法从用法中推断出来。

const myApi = myMethod(NewsApi);

在上面的例子中,myApi 不是 NewsApi 类型,而是 NewsApi|CommentsApi|FileApi 类型。 是否可以将 return 类型显式设置为输入 api 类型的实例?

如果您可以将数组的定义更改为只读元组:

const APIS = [NewsApi, CommentsApi, FileApi] as const;

然后您可以使用查找类型获得可能数组值的并集:

type ApiConstructors = typeof APIS[number];

function myMethod<T extends InstanceType<ApiConstructors>>(apiType: new () => T): T {
  return new apiType();
}

const api = myMethod(NewsApi); // api is of type NewsApi

InstanceType 用于获取构造函数实例类型的实用程序。

Playground