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)
CodePudding user response:
instead of parseInt use Number something like
Number(x)
CodePudding user response:
To add another option, you could simply make sure that what's passed to parseInt is a string using a template string:
parseInt(`${x}`)
CodePudding user response:
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.
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.
