Typescript – 将字符串 URL 转换为 TypeScript 中的对象类型

huangapple go评论62阅读模式
英文:

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&lt;T&gt; = T extends `/${infer U}` ? U : never;
type TUrl&lt;T&gt; = { [k in KeyUrl&lt;T&gt;]: string };

// --------------------------------------------- this line work
const url = &quot;/path&quot;;
const obj = {} as TUrl&lt;typeof url&gt;;
obj.path // work;

// --------------------------------------------- this line error
const url = &quot;/path/path2&quot;;
const obj = {} as TUrl&lt;typeof url&gt;;
obj.path // Property &#39;path&#39; does not exist;
obj.path2 // Property &#39;path2&#39; 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&lt;T&gt; = T extends `/${infer U}/${infer R}` ? U | KeyUrl&lt;`/${R}`&gt; : 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

huangapple
  • 本文由 发表于 2023年2月6日 14:47:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定