将 ValidatorJS isISIN 转换为 Typescript 并出现错误?

Converting ValidatorJS isISIN to Typescript and getting error?

isISIN 从 validatorjs 转换为 typescript 时出现以下错误:


(parameter) character: string
No overload matches this call.
  The last overload gave the following error.
    Type 'number' is not assignable to type 'string'.ts(2769)
lib.es5.d.ts(454, 53): The expected type comes from the return type of this signature.
lib.es5.d.ts(454, 5): The last overload is declared here.

这是代码:

  const checksumStr = target.replace(/[A-Z]/g, character => (parseInt(character, 36)));

VSCOde 在 (parseInt(character, 36))) 下画了一条红线,并带有错误。

想法? parseInt 不应该在那里吗?

这是整个方法,仅供参考:

/**
 * Test whether the target string is an ISBN number.
 * 
 * @param target The string
 * @return true if the `target` string is an ISIN number, false otherwise
 */
export function isISIN(target:string) {
  assertString(target);
  if (!isin.test(target)) {
    return false;
  }

  const checksumStr = target.replace(/[A-Z]/g, character => (parseInt(character, 36)));

  let sum = 0;
  let digit;
  let tmpNum;
  let shouldDouble = true;
  for (let i = checksumStr.length - 2; i >= 0; i--) {
    digit = checksumStr.substring(i, (i + 1));
    tmpNum = parseInt(digit, 10);
    if (shouldDouble) {
      tmpNum *= 2;
      if (tmpNum >= 10) {
        sum += tmpNum + 1;
      } else {
        sum += tmpNum;
      }
    } else {
      sum += tmpNum;
    }
    shouldDouble = !shouldDouble;
  }

  return parseInt(target.substr(target.length - 1), 10) === (10000 - sum) % 10;
}

发生这种情况是因为 parseInt returns a number and string.prototype.replace 期望收到 string 作为替换。

无论如何,代码有效,这应该是一个警告。

要修复它,请将 parseInt 结果转换为字符串。类似于:

  const replacer = character => {
    const intValue = parseInt(character, 36);
    return intValue? intValue.toString() : ''
  }

  const checksumStr = target.replace(/[A-Z]/g, replacer);