首页 > 解决方案 > String.fromCharCode vs '0x' 的 TypeScript 错误

问题描述

我需要任何建议来解决这个问题!错误:

('0x' + p1);

错误日志:

 TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

代码 :

export function encodeString(str): any {
  // first we use encodeURIComponent to get percent-encoded UTF-8,
  // then we convert the percent encodings into raw bytes which
  // can be fed into btoa.
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
    function toSolidBytes(match, p1) {
      return String.fromCharCode('0x' + p1);
    }));
};

标签: typescript

解决方案


那这个呢:

return String.fromCharCode(parseInt('0x' + p1, 16));

您需要使用 parseInt(16表示十六进制)将 UTF-8 代码字符串转换为整数。然后,将它传递给 String.fromCharCode() 函数。

希望能帮助到你。


推荐阅读