使用泛型参数和类型守卫
在遍历元组类型参数时,可以使用泛型参数和类型守卫来正确地获取元组中的每个元素。示例代码如下:
function mapTuple(arr: T, mapFn: (value: T[number], index: number, array: T) => any): any[] {
return arr.map(mapFn);
}
// Example usage:
const fruitTuple = ["apple", "banana", "orange"] as const;
const mappedFruit = mapTuple(fruitTuple, (fruit) => fruit.toUpperCase());
console.log(mappedFruit); // Output: ["APPLE", "BANANA", "ORANGE"]
在上述代码中,泛型参数T
继承了任何数组类型,将该数组传递给函数mapTuple
时,T
的值将被解析为数组元素的元组类型。T[number]
表示T
中每个元素的类型,并且具有number
类型的索引。因此,我们可以使用它来定义mapFn
的参数类型,以便可以正确地处理每个元素。最后,使用arr.map(mapFn)
将映射后的数组返回。
下一篇:遍历元组列表