1.TS 不一样的类型怎么合并?
// 合并两个对象类型
type MergeObject<T extends Record<string, string>, U extends Record<string, string>> = {
}
type MergeObject<{a: string}, {b: number}>; // => {a: string, b: number}
2.
题目:
type formateParams<T>(arg: T) {}
type F= formateParams("a=1&b=2&c=3"); //=> {a:1,b:2, c:3}
答:
type _Split<
T extends string,
I extends string
> = T extends `${infer H}${I}${infer Rest}` ? [H, ..._Split<Rest, I>] : [T];
type _Map<T extends string[], U extends any[] = []> = T extends [
infer H,
...infer Rest extends string[]
]
? H extends `${infer K}=${infer V}`
? _Map<Rest, [...U, { [key in K]: V }]>
: never
: U;
type MergeObject<
T extends Record<string, string>,
U extends Record<string, string>
> = {
[K in keyof T | keyof U]: K extends keyof T
? K extends keyof U
? [T[K], U[K]]
: T[K]
: U[K & string];
};
type MergeObjectArray<
T extends Record<string, string>[],
U extends {} = {}
> = T extends [
infer H extends Record<string, string>,
...infer Rest extends Record<string, string>[]
]
? MergeObjectArray<Rest, MergeObject<U, H>>
: U;
type FormateParams<T extends string> = MergeObjectArray<_Map<_Split<T, "&">>>;
function _formateParams<T extends string>(querystring: T): FormateParams<T> {
return querystring
.split("&")
.map((item) => item.split("="))
.reduce((prev, [key, value]) => {
prev[key] = value;
return prev;
}, {} as Record<string, string>) as any;
}
const res = _formateParams("a=1&b=2&c=3&a=5&b=6");