Is there way to dynamically create a string literal type from a string, other than making an array from the string and then extracting its type using typeof, as shown in this answer?
const url = 'text'
const URL = [url]
type P = (typeof URL)[number];
EDIT What I am trying to achieve is build, a method which based on the given string(endpoint URL) will be able extract required by that endpoint params which I need to provide.
export type ExtractRouteParams<T> = string extends T
? Record<string, string>
: T extends `${infer _Start}:${infer Param}/${infer Rest}`
? { [k in Param | keyof ExtractRouteParams<Rest>]: string }
: T extends `${infer _Start}:${infer Param}`
? { [k in Param]: string }
: {};
ExtractRouteParams is a type which based on the given string return my type which defined what kind of params are needed. Its works completely fine when I use it like that.
type Test = ExtractRouteParams<'actions/:actionId/test/:testId'>
But I would like it to work more dynamicaly. I have create an factory URL method within which I want to create type based on the URL provided as parameter. That method return generic class (Based on that dynamic type) which contain method to create url.
export function urlFactory(url: string) {
type P = typeof url;
return new InterpolateUrl<P>();
}
class InterpolateUrl<T extends string> {
url(params: ExtractRouteParams<T>): void {
}
}
const endpoints = {
endpoint: urlFactory(
'actions/:actionId/test/:testId'
)
};
Unfortunately InterpolateUrl class method url does not properly points required params. In compared, type Test does.
Here playground