Skip to content

Eliminate the need to cast from Object to JsonObject #23567

@rsimha

Description

@rsimha

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 JsonObject in amp.extern.js to make most of the casts unnecessary

    /**
    * 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 is parseJson() from src/json.js, but it doesn't work for cases where a non-null JsonObject is expected

    amphtml/src/json.js

    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 is isObject() from src/types.js, but it doesn't work when a JsonObject is expected

    amphtml/src/types.js

    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

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions