-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Eliminate the need to cast from Object to JsonObject #23567
Description
This came out of the discussions at #23559 (comment) and #23559 (comment)
The AMP codebase contains hundreds of casts from Object to JsonObject.
-
I wonder if there's a way to modify the declaration of
JsonObjectinamp.extern.jsto make most of the casts unnecessary
amphtml/build-system/amp.extern.js
Lines 57 to 65 in 6b86000
/** * A type for Objects that can be JSON serialized or that come from * JSON serialization. Requires the objects fields to be accessed with * bracket notation object['name'] to make sure the fields do not get * obfuscated. * @constructor * @dict */ function JsonObject() {} -
For converting to
JsonObject, there isparseJson()fromsrc/json.js, but it doesn't work for cases where a non-nullJsonObjectis expected
Lines 104 to 113 in c4a663d
/** * Simple wrapper around JSON.parse that casts the return value * to JsonObject. * Create a new wrapper if an array return value is desired. * @param {*} json JSON string to parse * @return {?JsonObject} May be extend to parse arrays. */ export function parseJson(json) { return /** @type {?JsonObject} */ (JSON.parse(/** @type {string} */ (json))); } -
For checking if a variable is an
Object, there isisObject()fromsrc/types.js, but it doesn't work when aJsonObjectis expected
Lines 48 to 55 in c4a663d
/** * Determines if value is actually an Object. * @param {*} value * @return {boolean} */ export function isObject(value) { return toString(value) === '[object Object]'; }
Related to #23425