-
Notifications
You must be signed in to change notification settings - Fork 12.2k
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
JSON.parse interface should allow any type as first argument #11842
Comments
While all objects have a |
Is that really relevant, though? I mean, this is how |
Everything in JavaScript has defined behavior. But these things are all super sketchy and much more likely to be a bug. |
Hmmm...good points. There are plenty of cases where you would want to do such a thing, like |
declare global {
interface JSON {
parse(text: Buffer, reviver?: (key: any, value: any) => any): any;
}
} Solves the problem nicely but I realize that's beside the point. Semantically |
It may be worth noting that the current version of Douglas Crockford's reference implementation does not call |
Well, as @nicknisi mentioned, the ES2015 spec does specify that the first argument to |
@jason0x43 I was looking for the intent of the API author. That is why I referenced the reference implementation. Good point that it is in fact the abstract operation |
D'oh, here's the ES2015 reference (pretty much the same, as is the ES2017 draft). But yes, that was my original question, too (author intent). It would have been easy enough to state that |
@jason0x43 I think your interpretation is correct. If you read the "Section 4: Parsers" of rfc4627, it states that
Interestingly, older versions of ecma262, such as ES5.1, explicitly call out the above, stating that such extensions would be in violation of the ECMAScript spec. ES5.1 section 15.12 This restriction is still stated in the current draft, see ecma262/#sec-json-object, but the informative link to original rfc4627 is no longer present. |
Nearly all of the runtime behavior is specified to coerce inputs using the corresponding primitive coercion routine. For example, the multiplication operator |
Per the ES5 spec,
JSON.parse
shouldtoString
the first argument passed toparse
. However, the interface in lib.d.ts states the first argument must be a string.This causes issues as shown in the code below where a Buffer is passed to
JSON.parse
TypeScript Version: 2.0.3
Code
Expected behavior:
No tsc errors should be thrown, as the first argument's
toString
method will be called.Actual behavior:
tsc: TS2345: Argument of type 'Buffer' is not assignable to parameter of type 'string'.
The text was updated successfully, but these errors were encountered: