Home > Software engineering >  Typescript conversion of string to integer
Typescript conversion of string to integer

Time:04-26

I am trying to convert a string to an integer in TypeScript, this is done with the parseInt method. Here is the issue the string is coming from and environmental variable so its type is string || undefined but the parseInt method requires an argument of type string. How can I solve the typescript error of the wrong argument type to the parseInt method? since the process.env is of type string || undefined.

CodePudding user response:

You should use an if statement.

if(value === undefined) return;
return parseInt(value);

In this way, you will also prevent an error that may occur.

CodePudding user response:

Apart from parseInt, we also have an alternative to convert a string to a number using unary operator with string...

function parse_using_parseInt(string_as_number: string | undefined) {
    if((string_as_number || '').trim()) {
        return parseInt((string_as_number || '').trim(), 10);
    }
    return NaN;
}

function parse_using_plus(string_as_number: string | undefined) {
    if((string_as_number || '').trim()) {
        return  (string_as_number || '').trim();
    }
    return NaN;
}

Check the examples and pick what is suitable.


Illustration

"use strict";

function parse_using_parseInt(string_as_number) {
  if ((string_as_number || '').trim()) {
    return parseInt((string_as_number || '').trim(), 10);
  }
  return NaN;
}

function parse_using_plus(string_as_number) {
  if ((string_as_number || '').trim()) {
    return  (string_as_number || '').trim();
  }
  return NaN;
}
console.log('Using parseInt: ', parse_using_parseInt(undefined));
console.log('Using parseInt: ', parse_using_parseInt("undefined"));
console.log('Using parseInt: ', parse_using_parseInt("123"));
console.log('Using parseInt: ', parse_using_parseInt("123xyz")); //<-- Partially parsed as 123, What is expected for this input
console.log('Using parseInt: ', parse_using_parseInt("xyz123"));
console.log('Using plus: ', parse_using_plus(undefined));
console.log('Using plus: ', parse_using_plus("undefined"));
console.log('Using plus: ', parse_using_plus("123"));
console.log('Using plus: ', parse_using_plus("123xyz")); //<-- This parses as NaN, unlike parseInt
console.log('Using plus: ', parse_using_plus("xyz123"));

  • Related