【问题标题】:Type 'string[]' is not assignable to type 'never[]'. typescript类型 \'string[]\' 不可分配给类型 \'never[]\'。打字稿
【发布时间】:2022-08-14 21:23:29
【问题描述】:

我有这样的代码:

export const combineUrlParams = (url = \"\", params: object) => {
  const keys = Object.keys(params);
  const paramUrl = keys
   .reduce(
     (result, key) =>
       params[key] !== undefined && params[key] !== null && params[key] !== \"\"
       ? [...result, `${key}=${params[key]}`]
       : [...result],
       []
   )
   .join(\"&\");
  return `${url}?${paramUrl}`;
};

它得到如下错误:

类型 \'string[]\' 不可分配给类型 \'never[]

类型 \'string\' 上不存在属性 \'join\'

我将它从 javascript 复制到打字稿。有人可以帮我解决这个问题吗?

    标签: typescript


    【解决方案1】:

    [] 是一个空数组,因此打字稿无法推断其中允许使用哪种值。

    你可以是明确的:

    ([] as string[])
    

    也就是说,你的函数还有很多其他问题(比如没有转义数据中的特殊字符),你正在重新发明a wheel that is built into browsers

    const url = new URL("https://example.com");
    const data = { foo: "bar", baz: 123, needsEscaping: "1&2=3" };
    url.search = new URLSearchParams(data);
    console.log(url.toString());

    【讨论】:

      猜你喜欢
      • 2022-11-04
      • 1970-01-01
      • 2021-09-21
      • 2022-01-17
      • 2021-10-11
      • 2019-07-09
      • 1970-01-01
      • 2020-06-29
      • 2019-04-10
      相关资源
      最近更新 更多