URLSearchParams不接受字符串


const sortString = req.query.sort as string
const params = Object.fromEntries(new URLSearchParams(sortString))

现在,当我进入实现,我得到:

declare var URLSearchParams: {
prototype: URLSearchParams;
new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
toString(): string;
};

现在,我很困惑为什么它不能在Typescript上工作,因为它应该接受字符串。

如何将URL参数转换为JavaScript对象?

No overload matches this call.
Overload 1 of 2, '(entries: Iterable<readonly [PropertyKey, any]>): { [k: string]: any; }', gave the following error.
Argument of type 'URLSearchParams' is not assignable to parameter of type 'Iterable<readonly [PropertyKey, any]>'.
Property '[Symbol.iterator]' is missing in type 'URLSearchParams' but required in type 'Iterable<readonly [PropertyKey, any]>'.
Overload 2 of 2, '(entries: Iterable<readonly any[]>): any', gave the following error.
Argument of type 'URLSearchParams' is not assignable to parameter of type 'Iterable<readonly any[]>'.
Property '[Symbol.iterator]' is missing in type 'URLSearchParams' but required in type 'Iterable<readonly any[]>'.ts(2769)

错误说明传递给fromEntries的参数必须是可迭代的,而不是。看看TS的定义,URLSearchParams在https://github.com/microsoft/TypeScript/blob/2f13eba42c76d02f2e5c79060d6018ee8c7fecc9/lib/lib.dom.iterable.d.ts#L285中被定义为可迭代的,所以很可能这个定义没有被加载到项目的TS配置中。

最新更新