【问题标题】:Typescript - string url to object type in tsTypescript - ts 中对象类型的字符串 url
【发布时间】:2023-02-06 17:05:17
【问题描述】:

如何将字符串 url 转换为 ts 中的对象类型?

示例代码:

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;

谢谢。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你的问题是 ${infer U} 很贪婪,它吃掉了所有的字符串。

    所以对于/path/path2,它将获得整个字符串,因为它不会拆分它。在创建定义 KeyUrl 时需要考虑到这一点。这样的事情应该有效:

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

    它的作用是获取path 并检查是否有一个或多个段,然后用剩余路径调用KeyUrl

    您可以查看更复杂的示例here

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 2021-11-26
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多