Minimal, Complete, and Verifiable Example (MCVE)
(try using the autocomplete on the parameter of the function f
to see what it achieves)
I am currently working on creating a recursive template literal to validate if the strings passed to a function align with the REST approach of my API.
So far, I have been successful in making simple examples work, such as version
and health/check
.
However, I am looking to extend this functionality to allow routes with parameters embedded in them.
While the route users/[PARAM]
is accepted without any issues and shows up in the autocomplete for parameters, users/12
does not pass validation. The problem seems to lie at the end of the Dive
type:
`${k & DiveKey}/${typeof param | string}`
If I utilize
${k & DiveKey}/${typeof param}
, I achieve the expected outcome.
Using ${k & DiveKey}/${string}
allows it to work, but the parameter users/[PARAM]
no longer appears in the autocomplete, making it less visible to developers utilizing the function.
Therefore, my question boils down to: Is there a way to retain users/[PARAM]
in the autocomplete while also accepting users/12
as an input?
Thank you in advance for your assistance.
Code Snippet
export type RestEndpoint = Dive;
const param = '[PARAM]' as const;
type DiveKey = string | number;
type Dive<T = typeof API_REST_STRUCTURE> = keyof {
[k in keyof T as T[k] extends Record<any, any>
? `${k & DiveKey}/${Dive<T[k]> & DiveKey}`
: T[k] extends typeof param
? `${k & DiveKey}/${typeof param | string}`
: k]: any;
};
const API_REST_STRUCTURE = {
version: false,
health: { check: false },
users: param,
};
function f(p: RestEndpoint) {}
f('version');
f('health/check');
f('users/[PARAM]');
f('users/12');
Update 1: Here's how it looks when using ${string}
:
https://i.sstatic.net/vIjBu.png
And this is the result with typeof param
(notice that users/12
is rejected):