Converting a string URL to an object type in TypeScript

Is there a way to convert a string URL into an object type in TypeScript?

Here is some sample code:

type KeyUrl<T> = T extends `/${infer U}` ? U : never;
type TUrl<T> = { [k in KeyUrl<T>]: string };

// --------------------------------------------- This line works
const url = "/path";
const obj = {} as TUrl<typeof url>;
obj.path // It works;

// --------------------------------------------- This line throws an error
const url = "/path/path2";
const obj = {} as TUrl<typeof url>;
obj.path // Property 'path' does not exist;
obj.path2 // Property 'path2' does not exist;

Thank you.

Answer №1

The issue you are facing is that ${infer U} is overly eager and consumes the entire string.

For example, with /path/path2, it captures the complete string without splitting it. This aspect must be considered when defining KeyUrl. Below is a suggested solution:

type KeyUrl<T> = T extends `/${infer U}/${infer R}` ? U | KeyUrl<`/${R}`> : T extends `/${infer U}` ? U : never

This code examines the segments of the path to determine if there is more than one segment, recursively calling KeyUrl with the remaining path as needed.

You can find a more intricate example here

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

Adjust the colors dynamically based on specific data within a loop

My task involves populating a table with data. Specifically, I am focusing on coloring the data in the first year column according to certain conditions. The desired outcome is as follows: +--------+------------+------+------+ | YEAR | 2022 | 2021 ...

Nullable Object in Vue 3 Composition API

I am utilizing the Vue 3 Composition api along with Typescript to create pinch zoom functionality using the HammerJS package. In my Vue application, I am attempting to replicate a functional example implemented in JavaScript from CodePen: https://codepen. ...

What is the comparable alternative to promise<void> in observables?

I've been working with Angular using TypeScript and I'm attempting to return a promise from an observable. What is the correct way to accomplish this? So far, I have tried the following: of(EMPTY).toPromise() // error: Promise<Observable<n ...

How can I ensure thorough test coverage without relying on Testbed?

We have implemented some custom form control components with decorators as follows: @Component({ selector: 'value-selector', templateUrl: './selector.component.html', styleUrls: ['./selector.component.scss'], provid ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

What should I do about typescript and ES6?

An error occurred while running my code: [0] app/components/people/details/PersonDetailComponent.ts(27,35): error TS2339: Property 'person' is missing from type '{}'. Here is the code snippet in question: export class PersonDeta ...

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 ...

The attribute 'getValue' is not a valid property for the data type 'Subject<boolean>'

Currently, I am working with Angular2 and have a BehaviorSubject. isOpen$: Subject<boolean> = new BehaviorSubject<boolean>(true); When I try to retrieve the latest value using: isOpen$.getValue() It functions correctly, however, there is a ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

The project needs to either compile a comprehensive list of all files or adhere to an 'include' pattern

When working in VSCode, I came across this warning: https://i.sstatic.net/jvUsk.png The line of code that triggered the TypeScript warning is: import packageJson from "../package.json"; Interestingly, the project builds and lints without any issues: $ ...

Stringified HTML code showcased

When working with Angular, I have encountered an issue where I am calling a function inside an .html file that returns a string containing a table element. My goal is to convert this string into HTML code. I attempted to use [innerHtml]: <p [innerHtml ...

Unable to proceed with deployment due to the absence of the 'category' property in the '{}' type

Everything seems to be functioning properly - I can add and remove products, all with the properties I specified in the database. However, my deployment for production is being hindered by some errors that I'm encountering. ERROR in src\app&bsol ...

The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefine ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...

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 ...

Which Index Type is the best fit for my assignment?

Color, by default, is a string that is set to primary. However, when used as an index in the Colors array, I encounter an issue where it is recognized as an any type. This happens because a string cannot be used as an index on type '{..etc}' The ...

Assets in production encountering a 404 error - distribution glitch

Once the base href URL is added to index.html <base href="."> I proceed to run production mode using "ng build --prod" After encountering a 404 Error, I moved the dist folder into the xampp htdocs folder and included an error image ...

Encountering build errors while utilizing strict mode in tsconfig for Spring-Flo, JointJS, and CodeMirror

While running ng serve with strict mode enabled in the tsconfig.json, Spring-Flow dependencies are causing errors related to code-mirror and Model. https://i.sstatic.net/KUBWE.png Any suggestions on how to resolve this issue? ...

React throwing an error when trying to use inline fontWeight styling with Typescript

I am currently working on applying a CSS rule to a td element. const boldText = { fontWeight: 'bold' } <td style={boldText}>Content</td> Unfortunately, I am encountering the following error: [ts] Type '{ style: { fontWeig ...

Confirm the identity of a user by checking their email against the records stored in a MySQL database

I am currently working on creating a user verification system using email that is stored in a mySql database and utilizing express JS. The user is required to input their email before filling out any other forms. If the email is not found in the email tabl ...