TypeScript中如何创建支持任意数量类型参数的函数
如何创建支持任意数量类型参数的随机项选取函数?
当然可以!TypeScript的可变元组类型和泛型元组推断正好能满足你的需求,让函数支持任意数量的类型参数,同时保证输入参数和返回值的类型严格对应。
实现代码
function getRandomItems<T extends unknown[]>(...arrays: { [K in keyof T]: T[K][] }): T { const result = [] as unknown as T; for (let i = 0; i < arrays.length; i++) { const items = arrays[i]; const randomIndex = Math.floor(Math.random() * items.length); result[i] = items[randomIndex]; } return result; } // 示例使用 type Car = { brand: string }; const fruits = ['Apple', 'Orange', 'Banana']; const colors = ['Red', 'Green', 'Blue']; const cars: Car[] = [{ brand: 'Ferrari' }, { brand: 'Porsche' }]; // 类型自动推断,无需手动指定泛型 const result1 = getRandomItems(fruits, colors, cars); // result1 的类型是 [string, string, Car] // 也可以手动指定泛型顺序(比如调换参数顺序) const result2 = getRandomItems<string, Car, string>(fruits, cars, colors); // result2 的类型是 [string, Car, string]
原理说明
- 泛型元组约束:
T extends unknown[]让T代表最终返回的元组类型,比如[string, Car, string],支持任意长度的类型组合。 - 输入参数类型映射:
{ [K in keyof T]: T[K][] }会把元组T中的每个类型转换为对应数组类型,比如[string, Car, string]会被映射为[string[], Car[], string[]],确保每个输入参数的类型和泛型参数严格匹配。 - 类型安全断言:用
as unknown as T将空数组断言为目标元组类型,虽然TypeScript无法自动推断循环赋值的类型,但我们通过逻辑保证了每个位置的类型正确性。
这个实现完全满足你的三个要求:
- 支持任意数量的类型参数(只要是合法的元组长度)
- 输入参数数量和类型参数数量严格一致
- 返回的数组类型和输入的类型参数一一对应
内容的提问来源于stack exchange,提问作者Michal
相关产品推荐
相关产品推荐

