简体   繁体   English

打字稿中独立泛型类型的数组

[英]Array of independent generic types in typescript

I'm trying to write a function that will take an array of initialisation functions, along with their options. 我正在尝试编写一个函数,该函数将使用一系列初始化函数及其选项。 I am able derive the type of the options from the function, so I thought I should therefore be able to check that the options I provide are of the same type. 我可以从函数中导出选项的类型,因此我认为我应该能够检查我提供的选项是否具有相同的类型。

The example is a minimised version of this. 该示例是其最小化版本。 I think I need an independent generic for each array item, but I obviously don't know the size of the array. 我认为每个数组项都需要一个独立的泛型,但是我显然不知道数组的大小。

type O<T> = { a: T }
type E<T> = [O<T>, T]

const f = <T={}>(array: E<T>[]) => {}

f([
  [{ a: 4 }, 4],     //Works
  [{ a: "5" }, "5"]   //Doesn't work as T is set to number
])

The solution: 解决方案:

type O = { a: any }

type E<T extends O[]> = {
   [P in keyof T]: T[P] extends T[number] ? [T[P], T[P]["a"]] : never;
}  

const f = <T extends O[]>(...args: E<T>) => { }  

Or more generically as: 或更笼统地说是:

type E<T extends {}[], K extends keyof T[number]> = {
   [P in keyof T]: T[P] extends T[number] ? [T[P], T[P][K]] : never;
}

const f = <T extends O[]>(...args: E<T, "a">) => { }

It should be noted that I could not get this to work without using the rest parameter. 应该注意的是,如果不使用rest参数,我将无法正常工作。

Explanation: 说明:

Once I stopped focusing so much on a single generic for each element, using mapped types I managed to get to: 一旦我不再对每个元素都只关注一个泛型,就可以使用映射类型来实现:

type E<T extends { a: any }[]> = {
   [P in keyof T]:  [T[P], T[P]["a"]]
}

But got an error: Type '"a"' cannot be used to index type 'T[P]'. 但是出现错误:类型'“ a”'不能用于索引类型'T [P]'。

This turns out to be because using keyof with tuples includes non-number keys (eg 'length'). 原来是因为对元组使用keyof包含非数字键(例如“长度”)。 I found the solution on a Typescript Github issue ; 我在Typescript Github问题上找到了解决方案; only check the numeric keys. 只检查数字键。

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

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