How to parse string | number in Typescript?

How to parse string | number in Typescript?

Problem Description:

I need add 40 to a string | number type, and return a string | number. How is it possible in Typescript?

I thought parse it to number, then increase it and return it. But how can I parse a variable which is not sure is string, but it can be number? 🙂

tried this:

parseInt(x) – 44

but raised an

Argument of type 'string | number' is not assignable to parameter of type 'string'.
  Type 'number' is not assignable to type 'string'.ts(2345)

Solution – 1

instead of parseInt use Number something like

Number(x)

Solution – 2

By checking the type:

if (typeof x === "string") {
    x = Number(x); // Or `parseInt` or whatever
}
const result = x - 44;

After the if, TypeScript will know from flow analysis that x has been narrowed from string | number to number.

Playground example


For the parsing, see my answer here for your various options. parseInt stops at the first non-numeric character and returns whatever number it has at that point (rather than returning NaN), which may or may not be your desired behavior.

Solution – 3

To add another option, you could simply make sure that what’s passed to parseInt is a string using a template string:

parseInt(`${x}`)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject