我希望将函数的返回类型设置为元组,其长度与参数数组的长度相同,如果在构建时知道长度的话.否则,返回类型应为布尔array.
第一部分是有效的,但是,当构建时长度未知时,类型是没有任何类型的空元组.
type Tuple<
T,
Length extends number,
Accumulator extends T[] = [],
> = Accumulator["length"] extends Length
? Accumulator
: Tuple<T, Length, [...Accumulator, T]>;
function useHasPermissions<
const T extends {
schemaName: string;
action: string;
}[],
>(args: { permissions: T }): Tuple<boolean, T["length"]> {
return [] as any;
}
使用元组(构建时已知的长度)调用:
// const tup: [boolean, boolean, boolean]
const tup = useHasPermissions({
permissions: [
{
schemaName: "User",
action: "read",
},
{
schemaName: "User",
action: "create",
},
{
schemaName: "User",
action: "update",
},
],
});
使用动态数组调用(构建时长度未知):
const arr = useHasPermissions({
permissions: getAtRuntime(),
});
// Tuple type '[]' of length '0' has no element at index '0'.ts(2493)
// Should be: boolean[]
const a = arr[0];