Using TypeScript to extract types from properties with specific types

My current challenge involves working with a filter object derived from an OpenAPI spec. The structure of this object is illustrated below:

export interface Filters {
  field1: string[]
  field2: string[]
  field3: boolean
  field4: number
}

My goal is to create a new type by selecting specific properties from the filters interface based on their types:

The desired outcome would be something similar to:

export type MultivalueFields = Select<Filters, string[]>
// Resulting type will be 'field1' or 'field2'

I'm curious if there is a built-in solution for this problem or how one could achieve this desired outcome?

Answer №1

If you are looking to create a utility type, you can use the following code snippet:

type Values<T> = T[keyof T]
type Select<T, SelectType> = Values<{
  [Prop in keyof T]: T[Prop] extends SelectType ? Prop : never
}>

// An example usage: typeof A = 'field1'
type A = Select<{field1: string[], field2: string}, string[]>

Credit for this code goes to @captain-yossarian from Ukraine

Answer №2

Multiple variations of this concept exist. The most up-to-date method involves using the as clause in mapped types:


type SelectOptions<T, SelectionType> = keyof {
  [Property in keyof T as T[Property] extends SelectionType ? Property : never]: any
}

// Resulting in 'field1'
type Result = SelectOptions<{field1: string[], field5: string}, string[]>

Playground Link

A similar approach can also be used to select properties based on a specific type:


type PickBySelectionType<T, SelectionType> = {
  [Property in keyof T as T[Property] extends SelectionType ? Property : never]: T[Property]
}

// Results in { field1: string[]; }
type Result = PickBySelectionType<{field1: string[], field5: string}, string[]>

Playground Link

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

I'm encountering an issue with one of my routes not loading correctly in Angular 4 Universal

I have been working on implementing Universal and I believe I've made significant progress. My project is built on this seed. However, when I run "npm start", only the /about and /contact pages render successfully. The /home page does not render at al ...

The argument labeled as 'shop' does not fit the criteria for the parameter 'items' or 'cart'

I've been doing some research but haven't had any luck finding a solution. I'm fairly new to Angular and currently working on a webstore project. I followed a tutorial, but encountered an error along the way. import { select, Store } from & ...

Tips for transferring state information from a client to a server component within Nextjs?

Currently, I am working on a project where I need to read and write data from a locally stored .xml file that contains multiple <user> tags. The technology stack includes TypeScript and NextJS. The project is divided into three main components sprea ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

Issue with subscribing to a shared service in Angular 2

I've encountered some challenges with BehaviorSubject while using a shared service across three components: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export ...

Access the Ionic2 App through the Slider option

Trying out Ionic 2 and facing an issue. Created a default side-menu app from CLI with a slider. Need to start the actual side-menu app from the last slide on button click or anchor link. My app.ts: @Component({ templateUrl: 'build/app.html' }) ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

The correlation between methods in programming languages

Can a class or object be created with type constraints between methods? abstract class Example<T>{ abstract methodOne(): T abstract methodTwo (arg: T):any } I am looking to ensure that the argument of methodTwo is the same type as the return ty ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

The name is not found when using attribute, but it is found when using extends

Lately, I've encountered difficulties with creating large TypeScript modules, and there's one thing that has been puzzling me. Specifically, the following scenario doesn't seem to work: // file A.ts export = class A { } // file main.ts imp ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

What are the steps for designing personalized syncfusion grid-columns while still preserving the built-in search functionality of syncfusion?

Looking to transform the data coming from the backend, specifically mapping a user's status which is represented as a number to its corresponding string value. Considered using typescript for this mapping task, but it interferes with syncfusion' ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

Incorporate service providers into models with Ionic3/Angular4

I am seeking feedback from individuals with more experience than me to determine if my approach is correct. I am currently working on an Ionic3-Angular app that involves a CRUD functionality for "Clientes". From what I have researched, the recommended st ...

Experimenting with TypeScript Single File Component to test vue3's computed properties

Currently, I am in the process of creating a test using vitest to validate a computed property within a vue3 component that is implemented with script setup. Let's consider a straightforward component: // simple.vue <script lang="ts" set ...

Leveraging Angular 4 with Firebase to extract data from a database snapshot

My dilemma lies in retrieving data from a Firebase DB, as I seem to be facing difficulties. Specifically, the use of the "this" operator within the snapshot function is causing issues (highlighted by this.authState.prenom = snapshot.val().prenom) If I att ...

Error in typography - createStyles - 'Style<Theme, StyleProps, "root"

I'm encountering an error in a small React app. Here is a screenshot of the issue: The project uses "@material-ui/core": "4.11.3". In the codebase, there is a component named Text.tsx with its corresponding styles defined in Text.styles.tsx. The styl ...