简体   繁体   English

TypeScript中类型参数的可选计数

[英]Optional count of type parameters in TypeScript

I would like to create function with optional count of type parameters. 我想用可选的类型参数计数来创建函数。 For example, function accepts parameters, where each parameter is array and returns array, where nth item is random item from nth parameter: 例如,函数接受参数,其中每个参数是数组,然后返回数组,其中第n个项目是第n个参数中的随机项目:

const getRandomItems<T1, T2, T3>(...arrays: [T1[], T2[], T3[]]): [T1, T2, T3] = {
    const result = []

    for (const items of arrays) {
        result.push(items[Math.floor(Math.random() * items.length)])
    }

    return result
}

const fruits = ['Apple', 'Orange', 'Banana']
const colors = ['Red', 'Green', 'Blue']
const cars = [new Car('Ferrari'), new Car('Porsche')]

// E.g. ['Apple', 'Blue', new Car('Porsche')]
getRandomItems<string, string, Car>(friuts, colors, cars)

// E.g. ['Orange', new Car('Ferrari'), 'Red']
getRandomItems<string, Car, string>(friuts, cars, colors)

This function accepts 3 parameters and returns array with 3 parameters. 此函数接受3个参数,并返回具有3个参数的数组。 But can I create function, that: 但是我可以创建函数吗:

  • Accept any number of typed parameters, eg <T1, T2, T3, T4> , 接受任何类型的参数,例如<T1, T2, T3, T4>
  • Accept same number of parameters as type parameters: ...arrays: [T1[], T2[], T3[], T4[]] , 接受与类型参数相同数量的参数: ...arrays: [T1[], T2[], T3[], T4[]]
  • Returns array with same types as typed parameters: [T1, T2, T3, T4] ? 返回类型与键入参数相同的数组: [T1, T2, T3, T4]
// Something like this:
const getRandomItems<...T>(...arrays: [...T[]]): [...T] = {

}

You'll want to use a mapped type to loop over the type of the input and convert each array type into the type of its elements: 您将要使用映射类型来遍历输入的类型,并将每种数组类型转换为其元素的类型:

type UnwrapArray<T> = T extends (infer U)[] ? U : T;

type Result<T extends any[][]> = {
  [I in keyof T]: UnwrapArray<T[I]>;
}

function getRandomItems<T extends any[][]>(...arrays: T): Result<T> {
    const result = []

    for (const items of arrays) {
        result.push(items[Math.floor(Math.random() * items.length)])
    }

    return result as any;
}

First of all, we need a helper type UnwrapArray to extract the type of the elements from an array. 首先,我们需要一个辅助类型UnwrapArray来从数组中提取元素的类型。 See this SO answer for more information. 有关更多信息,请参见此SO答案

Next, we have the type for the return value of the function. 接下来,我们具有函数返回值的类型。 It takes type T which is a doubly nested array, iterates over all the keys [I in keyof T] (since this is an array, the keys are the index) and extracts the element type of each array UnwrapArray<T[I]> . 它采用类型T ,它是一个双重嵌套的数组,迭代所有键[I in keyof T] (因为这是一个数组,所以键是索引),并提取每个数组的元素类型UnwrapArray<T[I]>

Finally the function only takes one generic argument T with the same constraint as in Result . 最后,该函数只接受一个通用参数T ,该通用参数T具有与Result相同的约束。 This way it doesn't matter how many arguments are provided. 这样,提供多少个参数都没有关系。

Note: it is necessary to cast the result to any inside the function body as the compiler doesn't have a high enough understanding of what Result<T> actually is. 注意:有必要将结果强制转换为函数体内的any内容,因为编译器对Result<T>实际上是什么没有足够的了解。

Playground 操场

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

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