typescript - 在 TypeScript 中从元组尾部获取第 n 个类型

标签 typescript

我想知道是否有一种方法可以从元组类型的尾部访问第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() 行为的实用程序类型,正如我(半开玩笑地)suggestedmicrosoft/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

但是它有效。

Playground link to code

关于typescript - 在 TypeScript 中从元组尾部获取第 n 个类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77586781/

相关文章:

typescript - 当启用标志 --strictNullChecks 时,null 不可分配给 void

typescript - 从方法装饰器获取方法签名

typescript - 泛型函数子类型约束错误和混淆

node.js - 使用导入而不是 require() 时带有 uuid 的 MongooseError

javascript - es6 特性不在 TypeScript 中编译

typescript - 等待非 Promise 函数时没有 typescript 警告

angular - "Can' t read the url"error for angular2 dynamic components with templateUrl

swift - 如何使用 typescript 将快照值转换为字典值?

javascript - Angular 2 - 同时发出多个 HTTP 请求

c# - 工具版本不支持 VsTsc 任务