我想知道是否有一种方法可以从元组类型的尾部访问第n个类型,例如...
type UserType = 'vendor' | 'customer' | 'staff';
type SignUpParameters = [string, string, boolean, UserType];
type isAdmin = NthTypeOfTuple<SignUpParameters, -2>; // boolean
最佳答案
没有内置功能可以执行此操作。对于能够实现此功能的功能有各种请求,例如 microsoft/TypeScript#26382这将允许您计算类似 T['length'] - 2
的内容在类型级别和索引上这样。
现在,您可以编写自己的实用程序类型以这种方式工作,但它几乎肯定会出现奇怪的边缘情况,并且需要 recursive conditional types运行于 variadic tuples .
一种可能的方法是构建 At<T, I>
用于模拟 Array.prototype.at()
行为的实用程序类型,正如我(半开玩笑地)suggested在 microsoft/TypeScript#47660 :
type Reverse<T extends readonly any[], U extends any[] = []> =
T extends readonly [infer F, ...infer R] ? Reverse<R, [F, ...U]> : U
type At<T extends readonly any[], I extends number> =
`${I}` extends `-${infer J}` ?
[never, ...Reverse<T>] extends infer R ?
J extends keyof R ? R[J] :
undefined :
never :
T[I];
Reverse<T>
类型是 tail-recursive conditional type反转一个元组,然后 At<T, I>
使用template literal types去掉减号 I
如果是负数,则索引到 T
的移位反向版本。是的,这太糟糕了:
type UserType = 'vendor' | 'customer' | 'staff';
type SignUpParameters = [string, string, boolean, UserType];
type IsAdmin = At<SignUpParameters, -2>;
// type IsAdmin = boolean
但是它有效。
关于typescript - 在 TypeScript 中从元组尾部获取第 n 个类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77586781/