Filtering strings with the same suffix

Here is a code snippet I am working with:

type RouterQuery = keyof AppRouter['_def']['queries'];

This code defines the following type:

type RouterQuery = "healthz" | "post.all" | "post.byId" | "category.all" | "category.byId" | "course.all" | "course.featured"

My goal is to extract only strings that contain the '.all' postfix.

The desired extracted type should be:

type RouterQueryAll = "post.all" | "category.all" | "course.all"

Any solutions on how I can achieve this?

Answer №1

type FilteredRouterQuery = Extract<RouterQuery, `${string}.all`>

By utilizing the Extract utility in TypeScript, you can selectively extract types from a union that conform to a specific type. In this case, `${string}.all` represents a template literal type designed to match any strings ending with .all.

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

Setting attributes within an object by looping through its keys

I define an enum called REPORT_PARAMETERS: enum REPORT_PARAMETERS { DEFECT_CODE = 'DEFECT_CODE', ORGANIZATION = 'ORGANIZATION' } In addition, I have a Form interface and two objects - form and formMappers that utilize the REPOR ...

The term 'Employee' is typically used as a classification, but in this context, it is being treated as a specific value

I am encountering an issue while trying to define a variable as type Employee. The error message 'Employee' only refers to a type but is being used as a value here. ts(2693) keeps appearing. Here is my show-api.ts code: import { Component, OnIni ...

What is the proper way to reference a computed symbol that has been inherited as a function in an extended class

As a newcomer to Typescript, my understanding of the code might be lacking. I am currently working with the Klasa framework, which is built on top of Discord bot framework using Discord.js. The framework recently introduced plugin functionality and there a ...

What is the method for transmitting a URL API from an ASP.NET Core server to my Angular 2 single application?

Is there a way to securely share the url of the web api, which is hosted on a different server with a different domain, from my asp net core server to my client angular2? Currently, I am storing my settings in a typescript config file within my angular2 ap ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

Using Angular2's NgFor Directive in Components

I am faced with the challenge of converting a tree-like structure into a list by utilizing components and subcomponents in Angular 2. var data = [ {id:"1", children: [ {id:"2", children: [ {id: "3"}, {id: "3"}, {i ...

Creating a union type from an array that is not a literal (using `Object.keys` and `Array.map`)

Can a union be derived from a non-literal array? I attempted the following: const tokens = { "--prefix-apple": "apple", "--prefix-orange": "orange" }; const tokenNames = Object.keys(tokens).map(token => toke ...

Challenges encountered when assigning values in a form with Material UI, Formik, and Typescript

When attempting to set the 'role' and 'active' values on a form, I encountered a couple of issues. The first problem arises from the fact that the selectors' original values are not being properly set. These values are fetched in ...

Utilize JavaScript destructuring to assign values to a fresh object

When working with JavaScript/Typescript code, what is a concise way to destructure an object and then assign selected properties to a new object? const data: MyData = { x: 1, y: 2, z: 3, p: 4, q: 5 } // Destructuring const { x, z, q } = data; // New O ...

Stop extra properties from being added to the return type of a callback function in TypeScript

Imagine having an interface called Foo and a function named bar that accepts a callback returning a Foo. interface Foo { foo: string; } function bar(callback: () => Foo): Foo { return callback(); } Upon calling this function, if additional pr ...

The type 'IContact[]' given does not match the expected type 'FetchContactsSuccessPayload' for the parameter

I've been diving into my project involving react redux-saga with TypeScript and I'm facing an issue with a type error within my saga file. This is my first experience with TypeScript. The error originates from the saga.ts file, specifically this ...

Issue encountered while trying to iterate through an observable: Object does not have the capability to utilize the 'forEach' property or method

I am currently following the pattern outlined in the hero.service.ts file, which can be found at this link: https://angular.io/docs/ts/latest/guide/server-communication.html The Observable documentation I referenced is available here: When examining my c ...

When I specify the type for the function parameter, an error occurs when I attempt to execute the function

When I assign a generic type to the function parameter and try to call the function, an error message pops up stating "This expression is not callable. Type unknown has no call signature." function a() { return 'abc' } function fun<T>(x: T ...

What is the best way to restrict the number of iterations in ngFor within Angular HTML

I want to use ngFor to display a maximum of 4 items, but if the data is less than 4, I need to repeat the loop until there are a total of 4 items. Check out this example <img *ngFor="let item of [1,2,3,4]" src="assets/images/no-image.jpg" styl ...

Utilizing a dictionary for comparing with an API response in order to generate an array of unique objects by eliminating duplicates

I currently have a React component that utilizes a dictionary to compare against an API response for address state. The goal is to map only the states that are returned back as options in a dropdown. Below is the mapping function used to create an array o ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Angular HighCharts - Retrieving chart data via API

My goal is to populate the data property of my chart with values obtained from an external API: . I've defined an Interface that matches the structure of the data: export interface ChartData{ item1: number; item2: number; ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...

Testing the Child Component's EventEmitter Functionality

In my child component, there is an event emitter that sends a boolean value when the style changes in the parent component: export class ExampleComponent implements OnInit, OnChanges { @Output() statusEvent = new EventEmitter<boolean>(); getS ...

How can you determine the number of times a particular digit appears around a specific position in a TypeScript array

(Utilizing Typescript for assistance) I am looking to determine the number of occurrences of the digit 2 surrounding a specific position within an array. The function takes in the position coordinates as parameters - param 1 for row and param 2 for column. ...