Home > other >  Get filtered type from a tuple
Get filtered type from a tuple

Time:08-21

I have a tuple which contains couple of objects.

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

I am looking for some generic Utility Type ( FilterRepos<T> ) where I can pass the type parameter and it should return me the filtered tuple type.

CodePudding user response:

We can use a tail-recursive type to construct a tuple by filtering out non-matching tuple elements.

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";
// }]

Playground

  • Related