TypeScript中的Variadic泛型类型? [英] Variadic generic types in TypeScript?

查看:97
本文介绍了TypeScript中的Variadic泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在TypeScript中创建一个函数,它接受一个构造函数数组并返回相应的实例数组。见下面的代码。

I'd like to make a function in TypeScript that takes an array of constructor functions and returns a corresponding array of instances. See code below.

请注意, getArray 方法非常不正确,它只是试图传达我的意图。

Note that the getArray method is wildly incorrect, it is just an attempt to convey my intent.

这可能是任何形式还是超出了TypeScript类型引擎的功能?

Is this possible in any form or is it beyond the capabilities of TypeScript's type engine?

class T1 {}
class T2 {}
class T3 {}
type AnyCon = new() => any;

function getOne<T_Con extends AnyCon>(con: T_Con): InstanceType<T_Con> {
  return new con();
}

function getArray<T_Cons>(cons: T_Cons): InstanceType<T_Cons>[] {
  return cons.map( (c: con) => new con() );
}

let t1: T1 = getOne(T1);
let [t2, t3]: [T2, T3] = getArray( [T2, T3] );


推荐答案

您可以在TS3.1及更高版本中执行此操作映射数组/元组类型。为元组更容易https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#tuples-in-rest-parameters-and-spread-expressions\"rel =nofollow noreferrer>其他参数它适用于数组参数,所以我将代之以:

You can do this in TS3.1 and above using mapped array/tuple types. It's easier to get tuples inferred for rest parameters than it is for array parameters, so I'll show that instead:

function getVariadic<T extends Array<AnyCon>>(...cons: T): {
  [K in keyof T]: T[K] extends AnyCon ? InstanceType<T[K]> : never
};
function getVariadic(...cons: AnyCon[]): any[] {
  return cons.map((c: AnyCon) => new c());
}

let [t2, t3]: [T2, T3] = getVariadic(T2, T3);

我认为这样做符合您的预期。希望有所帮助。祝你好运!

This behaves as you expect, I think. Hope that helps. Good luck!

编辑:如果你真的需要用数组来做它很容易输入函数但是有点更难以这样的方式调用它,以便将数组的顺序保存为元组:

if you really need to do it with an array it's easy to type the function but a little harder to call it in such a way that the order of the array is preserved as a tuple:

这篇关于TypeScript中的Variadic泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆