deno_std
deno_std copied to clipboard
flags: Skip parsing numeric-looking argument with no option
Is your feature request related to a problem? Please describe.
When parsing numeric-looking arguments which is not a flag, they are parsed as number. There are cases which it is not desired to do so. For example:
// $ deno run example.ts 000000 '000000'
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
console.dir(parse(Deno.args));
// output: { _: [ 0, 0 ] }
Describe the solution you'd like
There is string option to indicate argument names to be treated as string instead, but since the above argument is not a flag, it can't be specified with string option. It would be nice to have another option to indicate such argument.
Describe alternatives you've considered
Setting - as string works, but it skips number parsing all arguments in -. I can't think of another way.
I too have this issue.
BigInts are being cast to ints.
I see no workaround.
One possible workaround would be to check whether serializing/deserializing will yield the same result. If so, then parse it. Otherwise, leave it as a string to be handled by the end user.
function shouldParseAsNumber(val: string): boolean {
if (!isNumber(val)) {
return val;
}
return Number(val).toString() === val;
}
shouldParseAsNumber('0'); // true
shouldParseAsNumber('7'); // true
shouldParseAsNumber('1337'); // true
shouldParseAsNumber('00'); // false
shouldParseAsNumber('007'); // false
As for BigInt, it'd require a change to isNumber checking for the n prefix, however, as this is treated as a string, it can already be handled by the user just fine.
I was bitten by this unexpected behavior when I tried to parse a big number that couldn't be represented accurately as a number. I believe all non-flag arguments should be strings. No reason to try to be clever. The users should explicitly parse them to the type they want.
I have to agree. I think they should always be parsed as strings, would hate to introduce footguns. This is a breaking change though. How should we go about doing it?