Determine an expression based on a string in Typescript

Looking at the code snippet below, everything appears to be in order (view playground):

type PathParam<T> = T extends `${string}:${infer U}` ? U : never;

type Param = PathParam<"/post/:post_id">;
// type Param = "post_id"

However, things become a bit more complex when there is additional text following the path parameter.

type PathParam<T> = T extends `${string}:${infer U}` ? U : never;

type Param = PathParam<"/post/:post_id/likes/:like_id">;
// type Param = "post_id/likes/:like_id"

I understand why it fails in this scenario, but I am unsure how to only infer the pattern :${string} in typescript. In regex terms, it would be similar to /:[a-z_]+/g

Therefore, my inquiry is - how can I modify Param to be inferred as the subsequent type?

type Param = "post_id" | "like_id"

Answer №1

To successfully build a dynamically sized union, you will require the use of recursive types to create a loop.

Here is a suggested implementation:

type PathParam<T extends string, Res extends string = never> = 
    T extends `${string}:${infer U}/${infer Rest}` 
    ?  U | PathParam<Rest, Res> :
    T extends `${string}:${infer L}` 
    ?  L : Res;

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

Error: TypeScript React SFC encountering issues with children props typing

I am currently working with a stateless functional component that is defined as follows: import { SFC } from "react"; type ProfileTabContentProps = { selected: boolean; }; const ProfileTabContent: SFC<ProfileTabContentProps> = ({ selected, child ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

Different ways to invoke a general method with a deconstructed array as its argument

Calling a Generic Method with Deconstructed Array Parameters As of today, the only method to ensure typed safe inherited parameters is by using a deconstructed array and explicitly defining its type. This allows calling the parent method by utilizing the ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

Issues with Typegoose and Mongoose Enums when utilizing an array of strings

One of my enums is defined as follows: export enum Careers { WEB_DEVELOPMENT = 'Web Development', MOBILE_DEVELOPMENT = 'Mobile Development', UI_UX = 'UI/UX' } This particular enum is used as a mongoose property like so: ...

Retrieving information from the sessionStorage within app.module.ts

During the initialization of my application, it automatically redirects to the Login component. Here, I collect user data (username and password) and upon clicking the "Sign In" button, I send this information to the server. Upon receiving the Authorizatio ...

Any tips on silencing webpack's constant nagging about the "Critical dependency: require function is used in a way..." warning message?

My immediate goal is to resolve this warning. However, it seems that a different approach may be necessary. I have developed an npm library for date/time functions with most of the code being general-purpose and compatible with both Node.js and web browse ...

Encountering numerous issues during my attempt to perform an npm install command

After cloning a git repository, I encountered an issue when trying to run the app in the browser. Despite running "npm install," some dependencies were not fully installed. Upon attempting to run "npm install" again, the following errors were displayed: np ...

Is there a way to make PrismaClient return DateTime fields as Unix timestamps rather than JavaScript date objects?

When utilizing the PrismaClient for database interaction, DateTime fields are returned as JavaScript Date objects instead of Unix timestamp numbers. Despite being stored as Unix timestamp numbers in the database itself, I require the dates to be retrieved ...

How to retrieve a value from a base64-decoded string in Angular 6?

I successfully decoded a Base64 string using the xml2js library and obtained the following XML value: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="293" height="102" viewBox="0 0 293 102" xmlns="http://www.w3.org/2000/svg" ...

Integrate child component properties within the parent component

Looking to create a wrapper component that selects specific props from an inner component and includes additional custom props. The issue is that using pick will generate a type rather than an interface, limiting the ability to add more keys. How can I wor ...

Sometimes, it feels like TypeScript's async await does not actually wait for the task to complete before moving on

Recently, I have been transitioning to using the async await pattern more frequently instead of the traditional Promise syntax because it can help in keeping the code structure cleaner. After some experimentation, I felt like I had a good grasp on how to u ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Object.assign versus the assignment operator (i.e. =) when working with React components

Just a quick question: I've come across some answers like this one discussing the variances between Object.assign and the assignment operator (i.e. =) and grasp all the points made such as object copying versus address assignment. I'm trying to ...

A versatile method for transforming enums into arrays that can handle null values

Looking for a simpler way to create a TypeScript function that converts an enum to an array, including support for null values. Here's an example of what I'm trying to achieve: enum Color { RED = "Red", GREEN = "Green&qu ...

This property cannot be found on the specified type

So, I have this TypeScript function that will return one of two different objects based on the input value: function myfunc(isError:boolean): {response:string}|{error:string} { if(isError) return {error:''} return {response:''} } N ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...