
函数参数约束与结果推断
在 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> = { [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>, R]
: [];
type JoinWithAmpersand = T extends [
infer First extends string,
...infer Rest extends string[],
]
? Rest extends []
? First
: `${First}&${JoinWithAmpersand}`
: '';
type FinalBuildQueryString> = JoinWithAmpersand<
UnionToTuple>
>;
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 的结果类型。










