英文:
Typescript - string url to object type in ts
问题
如何将字符串 URL 转换为 TypeScript 中的对象类型?
示例代码:
type KeyUrl<T> = T extends `/${infer U}` ? U : never;
type TUrl<T> = { [k in KeyUrl<T>]: string };
// --------------------------------------------- 这一行正常工作
const url = "/path";
const obj = {} as TUrl<typeof url>;
obj.path // 正常工作;
// --------------------------------------------- 这一行出现错误
const url = "/path/path2";
const obj = {} as TUrl<typeof url>;
obj.path // 属性 'path' 不存在;
obj.path2 // 属性 'path2' 不存在;
谢谢。
英文:
How to make string url to object type in ts ?
sample code :
type KeyUrl<T> = T extends `/${infer U}` ? U : never;
type TUrl<T> = { [k in KeyUrl<T>]: string };
// --------------------------------------------- this line work
const url = "/path";
const obj = {} as TUrl<typeof url>;
obj.path // work;
// --------------------------------------------- this line 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;
Thanks.
答案1
得分: 0
Your problem is that ${infer U}
is greedy and it eats up all the string.
So for /path/path2
it will get the entire string as it doesn't split it. You need to take this into account when creating defining KeyUrl
. Something like this should work:
type KeyUrl<T> = T extends `/${infer U}/${infer R}` ? U | KeyUrl<`/${R}`> : T extends `/${infer U}` ? U : never
What this does is that it takes the path
and checks if there is one segment or more and then it calls the KeyUrl
with the remaining path.
You can check a more complex example here
英文:
Your problem is that ${infer U}
is greedy and it eats up all the string.
So for /path/path2
it will get the entire string as it doesn't split it. You need to take this into account when creating defining KeyUrl
. Something like this should work:
type KeyUrl<T> = T extends `/${infer U}/${infer R}` ? U | KeyUrl<`/${R}`> : T extends `/${infer U}` ? U : never
What this does is that it takes the path
and checks if there is one segment or more and then it calls the KeyUrl
with the remaining path.
You can check a more complex example here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论