函数参数约束与结果推断
在 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> = { [k in keyof tparams]: `${extract}=${tparams[k]}`;}[keyof tparams];type fullurl< tpath extends string, tparams extends record,> = `${tpath}${tparams extends record ? '' : '?'}${buildquerystring}`;function buildstringwithparams( path: tpath, params: tparams,): fullurl { 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;}
登录后复制
然而,原实现存在一些问题:
orderurl 被推断为 /order/detail?orderid=${string},而不是 /order/detail?orderid=123。productlisturl 被推断为联合类型,而不是 /product/list?type=electronics&pagesize=10&pageno=1。
解决方案
以下是如何修改函数以正确推断结果的:
type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;type UnionToTuple = UnionToIntersection U : never> extends () => infer R ? [...UnionToTuple<Exclude>, R] : [];type JoinWithAmpersand = T extends [ infer First extends string, ...infer Rest extends string[],] ? Rest extends [] ? First : `${First}&${JoinWithAmpersand}` : '';type FinalBuildQueryString<T extends Record> = JoinWithAmpersand< UnionToTuple<BuildQueryString>>;type FullUrl< TPath extends string, TParams extends Record,> = `${TPath}${TParams extends Record ? `?${FinalBuildQueryString}` : ''}`;// ......const orderUrl = buildStringWithParams('/order/detail', orderParams);const productListUrl = buildStringWithParams('/product/list', productListParams);
登录后复制
修改后的实现使用 uniontointersection 和 uniontotuple 类型的实用程序,将联合类型转换为交集类型和元组,然后使用 joinwithampersand 实用程序将查询字符串参数连接起来。这允许编译器准确地推断 orderurl 和 productlisturl 的结果类型。
以上就是TypeScript函数参数约束与结果推断:如何解决类型推断不准确的问题?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2650335.html