You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何正确为URLSearchParams指定参数类型?

解决TypeScript中URLSearchParams参数类型不匹配问题

错误原因

你定义的GetCoordsParams是一个嵌套了params属性的对象,但URLSearchParams构造函数接受的参数类型是string | string[][] | Record<string, string> | URLSearchParams | undefined,也就是直接的键值对集合,而非嵌套结构,因此出现类型不兼容错误。

解决方案

方案1:保持现有接口结构,传入嵌套的params属性

如果需要保留GetCoordsParams的外层结构,只需将params.params(即内层的键值对对象)传给URLSearchParams即可:

interface GetCoordsParams {
    params: Record<'city' | 'appid' | 'limit', string>;
};

export const createGetCoordsQuery = async (params: GetCoordsParams) => {
    // 传入内层的params属性,而非整个外层对象
    const query = new URLSearchParams(params.params).toString();
    await fetch(`http://api.geo.com/1.0/direct?q=${query}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
    });
};

方案2:简化参数类型,去掉嵌套结构

如果不需要外层的params嵌套,可以直接将函数参数类型定义为指定键的键值对集合:

// 直接定义为指定键的Record类型
type GetCoordsParams = Record<'city' | 'appid' | 'limit', string>;

export const createGetCoordsQuery = async (params: GetCoordsParams) => {
    const query = new URLSearchParams(params).toString();
    await fetch(`http://api.geo.com/1.0/direct?q=${query}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
    });
};

额外优化:使用URL对象规范拼接参数

手动拼接URL容易出现编码问题,推荐使用URL对象来管理搜索参数,更安全规范:

interface GetCoordsParams {
    params: Record<'city' | 'appid' | 'limit', string>;
};

export const createGetCoordsQuery = async (params: GetCoordsParams) => {
    const url = new URL('http://api.geo.com/1.0/direct');
    // 批量添加搜索参数
    Object.entries(params.params).forEach(([key, value]) => {
        url.searchParams.append(key, value);
    });
    await fetch(url.toString(), {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
    });
};

内容的提问来源于stack exchange,提问作者Jan Jankowski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:30:23