繁体   English   中英

来自类型数组的 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 的解决方案非常适合传入输入。 但是,无法从用法推断返回类型。

const myApi = myMethod(NewsApi);

在上述情况下,是myApi类型不是NewsApi ,但NewsApi|CommentsApi|FileApi 是否可以将返回类型显式设置为输入 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实用程序用于获取构造函数的实例类型。

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM