首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从元组获取筛选类型

从元组获取筛选类型
EN

Stack Overflow用户
提问于 2022-08-21 06:11:48
回答 1查看 26关注 0票数 1

我有一个元组,包含两个对象。

代码语言:javascript
复制
const repos = [
  { name: 'react', type: 'JS' },
  { name: 'angular', type: 'TS' },
] as const

const RepoTypes = typeof repos

const jsRepoTypes = FilterRepos<'JS'> // Should return the type object containing only JS

我正在寻找一些通用实用程序类型( FilterRepos<T> ),在这里我可以传递type参数,它应该返回过滤后的元组类型。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-21 06:19:29

通过过滤出不匹配的元组元素,我们可以使用尾递归类型来构造元组。

代码语言:javascript
复制
type FilterRepos<
  T extends string, 
  REPOS extends readonly any[] = typeof repos
> = 
  REPOS extends readonly [infer L, ...infer R] 
    ? L extends { type: T } 
      ? [L, ...FilterRepos<T, R>] 
      : FilterRepos<T, R>
    : []

type JsRepoTypes = FilterRepos<'JS'>
// type JsRepoTypes = [{
//     readonly name: "react";
//     readonly type: "JS";
// }, {
//     readonly name: "vue";
//     readonly type: "JS";
// }]

游乐场

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73432063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档