0

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)
t44
  • 3
  • 2

3 Answers3

0

instead of parseInt use Number something like

Number(x)
jitender
  • 10,238
  • 1
  • 18
  • 44
  • Why would that make any difference to TypeScript? Both `Number` and `parseInt` return numbers. – T.J. Crowder Nov 23 '22 at 10:10
  • @T.J.Crowder check this playground link you can see Number works fine with string | number.Also ``parseInt``` parses up to the first non-digit and returns whatever it had parsed so it will treat '123xyz' as number https://www.typescriptlang.org/play?ssl=2&ssc=13&pln=2&pc=22#code/DYUwLgBAHgXBDOYBOBLAdgcwD4TQVwFsAjEJAXgHIAWABgoG4AoAYwHs15XQA6YVjABQA5QiSQCoASklA – jitender Nov 23 '22 at 10:11
  • I see what you mean (`Number` accepts `any`), you might want to call that out explicitly as well as mentioning how markedly different `Number` and `parseInt` are. (`parseInt` works in your playground as well: https://www.typescriptlang.org/play?#code/DYUwLgBAHgXBDOYBOBLAdgcwgHwmgrgLYBGISEAvBAOQAsADNQNwBQAxgPZrwegB0wDhgAUABwCGSeCACSaMMKgBKJUA because of flow analysis) Better example: https://www.typescriptlang.org/play?#code/DYUwLgBAHgXBDOYBOBLAdgcwgHwmgrgLYBGISEAvBALICGYAFgHRK1oAmA9oQBQCUEADwQADEwCsEAPwQARABYRsiHEUBuAFABjTmnidQTYJww8ADrSTwQASTRgeUPnyA – T.J. Crowder Nov 23 '22 at 10:20
0

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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

parseInt(`${x}`)
DBS
  • 9,110
  • 4
  • 35
  • 53