首页 > web前端 > js教程 > 正文

TypeScript函数参数约束与结果推断:如何解决类型推断不准确的问题?

花韻仙語
发布: 2024-11-17 17:42:01
原创
971人浏览过

typescript函数参数约束与结果推断:如何解决类型推断不准确的问题?

函数参数约束与结果推断

typescript 中,我们可以定义一个函数,其第二个参数受第一个参数约束,从而在编译时推断出最终的结果。例如,我们需要合并路径和参数的函数,根据路径来约束所传参数,最终拼接路径和参数得出最终字符串。

type path2params = {
  '/order/detail': { orderid: string };
  '/product/list': { type: string; pagesize: string; pageno: string };
};

const orderparams: path2params['/order/detail'] = { orderid: '123' };
const productlistparams: path2params['/product/list'] = { type: 'electronics', pagesize: '10', pageno: '1' };
登录后复制

理想情况下,通过函数可以推断出 orderurl 为 /order/detail?orderid=123,productlisturl 为 /product/list?type=electronics&pagesize=10&pageno=1。

原始实现和问题

以下是我们自己的实现:

type buildquerystring<tparams extends record<string, string>> = {
  [k in keyof tparams]: `${extract<k, string>}=${tparams[k]}`;
}[keyof tparams];

type fullurl<
  tpath extends string,
  tparams extends record<string, string>,
> = `${tpath}${tparams extends record<string, never> ? '' : '?'}${buildquerystring<tparams>}`;

function buildstringwithparams<tpath extends keyof path2params, tparams extends path2params[tpath]>(
  path: tpath,
  params: tparams,
): fullurl<tpath, tparams> {
  const encodedparams = object.entries(params).map(([key, value]) => {
    const encodedvalue = encodeuricomponent(value);
    return `${encodeuricomponent(key)}=${encodedvalue}`;
  });
  const querystring = encodedparams.join('&');
  return `${path}${querystring ? '?' : ''}${querystring}` as fullurl<tpath, tparams>;
}
登录后复制

然而,原实现存在一些问题:

  • orderurl 被推断为 /order/detail?orderid=${string},而不是 /order/detail?orderid=123。
  • productlisturl 被推断为联合类型,而不是 /product/list?type=electronics&pagesize=10&pageno=1。

解决方案

以下是如何修改函数以正确推断结果的:

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void
  ? I
  : never;

type UnionToTuple<U> =
  UnionToIntersection<U extends any ? () => U : never> extends () => infer R
    ? [...UnionToTuple<Exclude<U, R>>, R]
    : [];

type JoinWithAmpersand<T extends any[]> = T extends [
  infer First extends string,
  ...infer Rest extends string[],
]
  ? Rest extends []
    ? First
    : `${First}&${JoinWithAmpersand<Rest>}`
  : '';

type FinalBuildQueryString<T extends Record<string, string>> = JoinWithAmpersand<
  UnionToTuple<BuildQueryString<T>>
>;

type FullUrl<
  TPath extends string,
  TParams extends Record<string, string>,
> = `${TPath}${TParams extends Record<string, string> ? `?${FinalBuildQueryString<TParams>}` : ''}`;

// ......
const orderUrl = buildStringWithParams('/order/detail', orderParams);
const productListUrl = buildStringWithParams('/product/list', productListParams);
登录后复制

修改后的实现使用 uniontointersection 和 uniontotuple 类型的实用程序,将联合类型转换为交集类型和元组,然后使用 joinwithampersand 实用程序将查询字符串参数连接起来。这允许编译器准确地推断 orderurl 和 productlisturl 的结果类型。

以上就是TypeScript函数参数约束与结果推断:如何解决类型推断不准确的问题?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号