Typescript: Creating a new type by filtering an interface for matching properties

Imagine you have an interface structured like this:

interface endpoints {
  "/api/user/{id}": {
    get: operations["getUserGET"];
  };
  "/api/user/add": {
    put: operations["addUsingPUT"];
  };
  ...
}

Is it possible to create a subtype that filters by HTTP methods such as get, put, post, etc?

The desired outcome would look something along these lines:

type getEndpoints = CoolFilter<endpoints, 'get'>

/* equivalent to: */
interface getEndpoints {
  "/api/user/{id}": {
    get: operations["getUserGET"];
  };
  /* only including GET methods in the interface */
}

Answer №1

If you want to filter based on the method present in a nested property, you can utilize the custom type below.

type MethodOf<T, M extends 'delete' | 'get' | 'post' | 'put'> = {
  [K in keyof T]: T[K] extends Record<M, unknown>
    ? Pick<T[K], M>
    : never
}

Here's how you can use it:

interface paths {
  "/api/user/{id}": {
    get: operations["getUserGET"];
  };
  "/api/user/add": {
    put: operations["addUsingPUT"];
  };
  ...
}

type getPaths = MethodOf<paths, 'get'>
//   ^? { "/api/user/{id}": { get: operations["getUserGET"] } }

Answer №2

It appears that the solution to your query involves utilizing the Pick utility type:

type fetchRoutes = Pick<routes, 'fetch'>;

However, it seems like there might be some confusion in your code snippet between type definitions and object literals, making it a bit unclear.

Additionally, it's worth mentioning that TypeScript convention suggests beginning type names with a capital letter - for instance, Routes, FetchRoutes, and so on.

Answer №3

If you want to narrow down your search by type, you can utilize the PickyByType utility. More details can be found here:

type ChooseByType<T, Value> = {
  [P in keyof T as T[P] extends Value | undefined ? P : never]: T[P];
};

For the key 'select', you can use

ChooseByType<T, {select: unknown}>

SuperFilter can now select all types with the specified property.

type SuperFilter<T, Property extends string> = ChooseByType<T, {[P in Property]: unknown}>

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

Accessing URL fragments in Next JS with context during the execution of getServerSideProps

I am trying to extract a URL fragment using getServerSideProps. The URL is structured like this: http://localhost:3000/some-folder#desiredParam=value Even though I pass the context as an argument to the getServerSideProps function, I am struggling to retr ...

Tips for including additional properties to a <button> element using ReactJS and Typescript

Currently, I am in the process of creating a unique component which consists of an ordinary <button> tag and has a new prop called aria-current. The issue at hand is that Typescript is flagging an error stating that this property does not exist with ...

Leveraging TypeScript unions within functions to handle and throw errors

As a newcomer to TypeScript, I've encountered an odd error that I need help with. I have various objects sending data to the server and receiving fresh data back of the same object type. These objects use a shared method for sending the data, so I ap ...

Change the keys of the object in the return statement

Scenario Imagine a scenario where a method called matter is returning an object in the form of return {content, data} Issue There is a conflict when the method is called a second time, as it overwrites any previous variables that were set from the return ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

Clear function of signature pad not working inside Bootstrap modal dialogue box

Currently, I'm working on implementing a signature pad dialogue box using Bootstrap modal. When the user clicks on the "Complete Activity" button, a dialog box should pop up with options for yes or no. If the user selects yes, another dialog box shoul ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...

Tips for invoking both a typescript arrow function and a regular javascript function within one event

Is it possible to call both a JavaScript function and a TypeScript function from the same onClick event in a chart? I am new to TypeScript and Angular, so I'm not sure if this is achievable. The issue at hand is that I need to invoke a JavaScript fun ...

The view fails to update when the object is modified

Within the acceptRequest function in child.component, the commissioner.requestAccepted property is set to false, and then the updated commissioner object is returned. Ideally, I want the button to be automatically removed from the view once the object is ...

Determine the category of a container based on the enclosed function

The goal is to determine the type of a wrapper based on the wrapped function, meaning to infer the return type from the parameter type. I encountered difficulties trying to achieve this using infer: function wrap<T extends ((...args: any[]) => any) ...

Exporting a class from an index.ts file may result in a problem where the injected constructor is

Utilizing an index.ts file to manage exports, following the guidelines outlined in the Angular 2 style guide (https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure), has been successful throughout my application deve ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Advanced type generics in Typescript

I've hit a roadblock in my attempt to ensure type safety for a function that should take an object and return a number. Despite numerous efforts, I haven't been successful. To give you a simple example (the actual application involves more comple ...

Resolving DOMException issue in Google Chrome: A Step-by-Step Guide

In my browser game, I am experiencing an issue with sound playback specifically in Google Chrome. Although the sound manager functions properly in other browsers, it returns a DOMException error after playing sounds in 50% of cases. I'm unsure what co ...

Guide to displaying an input box depending on the selection made in a Mat-Select component

I am working on a mat-select component that offers two options: Individual Customers and Organizational Customers. When selecting Individual Customers, the dropdown should display three options: First Name, Last Name, and Customer Id. However, when choosin ...

Tips for creating a vue-cli application that can be customized post-build:

I have a functioning vue-cli application that I can easily build. However, I now need to create a single deployable build that can be used on multiple servers. The challenge is that depending on the server, I will need to adjust some basic variables such a ...

Creating a Session Timeout feature for Ionic/Angular that includes resetting the timer with each new user interaction

Having trouble implementing a session timeout feature in my code. I need the timer to reset whenever a user interacts with the function. Can't figure out how to integrate similar code like the one provided as an example on Stack Overflow. This is the ...

Explain the concept of utilizing curried state handlers within a React and Typescript application

I am currently working on defining the function that will handle change events to update the state value accordingly. This is what I envision the implementation to look like: handleChange: ChangeHandler<State> = field => value => this.set ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...