Search code examples
javascripttypescriptparseint

Converting ValidatorJS isISIN to Typescript and getting error?


I'm getting the following error when converting isISIN from validatorjs to 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.

This is the code:

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

VSCOde draws a redline under (parseInt(character, 36))) with the error.

Thoughts? Should the parseInt not be there?

This is the entire method just for reference:

/**
 * 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;
}


Solution

  • This happens because parseInt returns a number and string.prototype.replace expects to receive a string as replacement.

    Anyway, the code works, that should be a warning.

    To fix it, transform the parseInt result to string. Something like:

      const replacer = character => {
        const intValue = parseInt(character, 36);
        return intValue? intValue.toString() : ''
      }
    
      const checksumStr = target.replace(/[A-Z]/g, replacer);