Obtain the selected type from a tuple after filtering

I have a tuple with multiple objects stored in it.

const repos = [
  { name: 'react', type: 'JS' },
  { name: 'angular', type: 'TS' },
] as const

const RepoTypes = typeof repos

const jsRepoTypes = FilterRepos<'JS'> // Expected to filter and return only the JS type object

I am interested in a generic Utility Type ( FilterRepos<T> ) where I can input the type parameter and receive the filtered tuple type.

Answer №1

Utilizing a tail-recursive method, we can effectively create a tuple by selectively removing tuple elements that do not match the specified criteria.

type FilteredTuples<
  T extends string, 
  TUPLES extends readonly any[] = typeof tuples
> = 
  TUPLES extends readonly [infer L, ...infer R] 
    ? L extends { type: T } 
      ? [L, ...FilteredTuples<T, R>] 
      : FilteredTuples<T, R>
    : []

type TypescriptRepoTypes = FilteredTuples<'typescript'>
// type TypescriptRepoTypes = [{
//     readonly name: "angular";
//     readonly type: "typescript";
// }, {
//     readonly name: "react";
//     readonly type: "typescript";
// }]

Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

Unable to utilize vue-cookies library in TypeScript environment

I have integrated vue-cookies into my app in the main.ts file: import VueCookies from 'vue-cookies'; ... const app = createApp(App) .use(IonicVue) .use(router) .use(VueCookies,{ expires: '30d', }); Despite adding the cookie v ...

The solution to enabling Type checking in this scenario is simple: Begin by addressing the issue of "Not assignable," followed by resolving any

After subscribing to an observable projected by a BehaviorSubject from a service, I encountered the following errors when trying to assign the subscribed value to a local variable: error TS2322: Type '{}' is not assignable to type 'DatosAdmi ...

Need to import a JSON file and convert it to an interface in order to ensure that all fields are included

I am facing an issue where I am attempting to parse a json file using require(). My goal is to convert it into a specific data type and have the conversion fail if the file does not contain all the necessary fields as defined by the interface. Below is my ...

What is the process for importing libraries from a different local directory?

What I mean by that title is: I have some code that was generated and now I am incorporating it into my Angular application. Currently, I am installing this code as a package using npm, but it is causing issues with my deployment setup. So, I would like ...

Encountering a problem with the 'string' parameter when using TypeScript

I keep encountering the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ barkingRoadProject: string[]; }'. No index signature with a paramet ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

Ways to pass a class list from a client to a webmethod using AJAX

I have a list of client-side classes in TypeScript that I need to send to a web method. Here is my TypeScript code: class MakeReportData { LocalName: string; FldSi: number; ViewSi:number; TypeName:string ; CheckBoxshow :boolean ; ...

What is the process for defining a state using React Native and TypeScript?

Recently, I've embarked on my journey with React Native and decided to incorporate TypeScript into my development process. As I attempted to set my state, an error popped up that reads as follows: An issue arose while trying to assign the argument &a ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

Develop a new flow by generating string literals as types from existing types

I'm running into a situation where my code snippet works perfectly in TS, but encounters errors in flow. Is there a workaround to make it function correctly in flow as well? type field = 'me' | 'you' type fieldWithKeyword = `${fiel ...

What is the process for retrieving information from Sanity?

Having trouble with creating a schema and fetching data from sanity. The console log is showing undefined. Not sure where I went wrong but suspect it's related to the schema creation. Testimonials.tsx interface Props { testimonial: [Testimonial] ...

Issues with Angular not reflecting data changes in the view after updates have occurred

I have a setup with two components. One is responsible for creating new data entries, while the other one is in charge of listing all the data stored in a database. The issue I'm facing is that even though the creation component successfully adds new ...

Trigger a table refresh to display updated information

When I select the select option to make an API call for a new datasource, my table appears before fetching data and it remains empty. Additionally, if I choose another select option, it displays the previous data from the previous selection. I have attemp ...

Need assistance with the Angular polyfill.ts file? Wondering where to place the polyfill code and how to manage it effectively?

Currently encountering an error in my Angular project that requires some 'polyfilling'. Due to the restriction on editing webpack.config.js directly, it seems necessary to work with the polyfill.ts file instead. The issue lies in the fact that An ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

The field list contains an unidentified column named 'Test.computerIDComputerID'

I am currently navigating through the syntax of typeORM and have been stuck troubleshooting an issue for quite some time. It appears that whenever I utilize the find() function in typeORM, a query is generated with a duplicated column from a relation. Here ...

Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query. let request = this.http.post(this.searchlUrl, payload).pipe( retryWhen(errors => errors.pipe(delay(100 ...

There are two modals present on the page, however only one of them is triggered for all actions in Angular 2

I'm encountering an issue with my page where I have set up two confirmation modals - one for resetting a form and another for deleting an item. Strangely, only the reset modal is being triggered for both actions and I can't figure out why. Could ...

Ways to break down a collection of multiple arrays

Looking to transform an array that consists of multiple arrays into a format suitable for an external API. For example: [ [44.5,43.2,45.1] , [42, 41.2, 48.1] ] transforming into [ [44.5,42], [43.2,41.2] , [45.1, 48.1] ] My current code attempts this ...