TypeScript函数返回类型适配问题:动态数组返回空元组而非boolean[]
解决方案
要实现「编译时已知数组长度返回对应长度boolean元组,未知则返回boolean数组」的需求,需要通过条件类型区分具体数字字面量和宽泛number类型,修复原类型在动态数组场景下返回空元组的问题。
修改后的代码
type Tuple< T, Length extends number, Accumulator extends T[] = [], > = Accumulator["length"] extends Length ? Accumulator : Tuple<T, Length, [...Accumulator, T]>; // 核心:判断长度类型是具体字面量还是宽泛number,返回对应类型 type Result<Length extends number> = number extends Length ? boolean[] : Tuple<boolean, Length>; function useHasPermissions< const T extends { schemaName: string; action: string; }[], >(args: { permissions: T }): Result<T["length"]> { return [] as any; }
原代码问题解析
原Tuple类型在处理宽泛number类型(动态数组的length类型就是number)时,初始累加器Accumulator是空数组,其length为0。由于0 extends number始终为true,类型递归直接终止,返回空元组[],导致访问数组索引时报错。
测试验证
编译时已知长度的场景
// const tup: [boolean, boolean, boolean] const tup = useHasPermissions({ permissions: [ { schemaName: "User", action: "read" }, { schemaName: "User", action: "create" }, { schemaName: "User", action: "update" }, ], });
动态数组场景
// 模拟运行时获取的数组 function getAtRuntime() { return [{ schemaName: "User", action: "read" }]; } const arr = useHasPermissions({ permissions: getAtRuntime() }); // 此时 arr 类型为 boolean[],访问索引不再报错 const a = arr[0];
内容的提问来源于stack exchange,提问作者Ruudy
相关产品推荐
相关产品推荐

