Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get filtered type from a tuple

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading