New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
encodeURIComponent should accept any value type #18159
Comments
Similar discussion can be found in #4002. We have chosen to be more strict with the standard library and only allow strings, not things that can be coerced into string by the engine. |
I think this is different than #4002, since it explicitly/transparently does coercion for the return value, not merely for a comparison value. I probably never intend to do |
Would take a PR for it. |
I just ran into this when trying to encode numbers, too. Doing something like the below code gives a compile-time error, which, as someone more used to plain JavaScript, was unexpected.
|
Is there a way to override the declaration in the mean time? |
Figured it out:
|
@jdalrymple Do you have time to submit PR , please ? |
Opened PR #31103 From this issue’s description:
I opted for the first solution (using |
…om 'string' to 'string | number | boolean'. Fixes #18159 (#31103) - According to the ECMAScript 5.1 spec (§15.1.3.4), 'encodeURIComponent' invokes the abstract operation 'ToString': https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4 - In the spec (§9.8), 'ToString' accepts an 'Undefined', 'Null', 'Boolean', 'Number', 'String' or 'Object' argument: https://www.ecma-international.org/ecma-262/5.1/#sec-9.8 - TypeScript’s 'StringConstructor' accepts an argument with type 'any': https://github.com/Microsoft/TypeScript/blob/b0100100a18d740ad0b7c626bc81b800b5273ece/lib/lib.es5.d.ts#L518
TypeScript Version: 2.5.2
Code
Expected behavior:
tsc compiles with no errors.
Actual behavior:
error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'.
Discussion:
encodeURIComponent
is currently defined liked this:In reality,
encodeURIComponent
accepts any value and coerces it to a string if necessary. The first step in its definition in the ES6 spec reads:It’s pretty common to pass
true
orfalse
or a number like0
or10
as a query parameter, for instance. Here are two possible ways to broaden the definition:The
any
option would be technically correct, but passingnull
orundefined
or a non-primitive value is usually a bug (in my experience). You can use your own judgment about how broadly theuriComponent
argument should be defined. I’m specifically interested in usingnumber
andboolean
.The text was updated successfully, but these errors were encountered: