Validating the Contents of Arrays using Closure-Compiler

When working with Google Closure, there is a question about initializing an Array of a specific @type{Array.<type>} and whether or not Google Closure will confirm the Array contents.

A test case has revealed that an {Array.<string>} seems to pass through an {Array.<number>} check, while a {string} is correctly blocked by the same check. Is this possibly an error on the part of someone new to GC?

This issue was tested using the Google Closure Service, resulting in only one expected error on September 12, 2013. Additional testing was performed on a local jar file (version v20130823) with ADVANCED_OPTIMIZATIONS and warning_level VERBOSE. The problem persists with the {Array.<string>} passing through the check.

For more information, refer to the documentation: Annotating for Google Closure

Your input on this matter would be greatly appreciated.

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @warning_level VERBOSE
// @language ECMASCRIPT5
// ==/ClosureCompiler==

/**
    Expected behavior - no warning:
    @type {Array.<number>}
*/
var a = [1,2,3,4];

/**
    Warning! Type mismatch as expected:
    @type {Array.<number>}
*/
var b = 'mismatch';    // {string} does not match {Array.<number>}

/**
    Unexpectedly no warning for type mismatch:
    @type {Array.<number>}
*/
var c = ['foo','bar']; // {Array.<string>} should not match {Array.<number>}


// prevent compile-to-zero
alert(a);
alert(b);
alert(c);

Note: Similar issues have been discussed in this related question, specifically regarding manually filling in the type of Array.push(). This current concern, however, focuses on initialization. Even after implementing suggested corrections and populating arrays with irrelevant data, it seems that Google Closure fails to detect discrepancies in type matching.

Edit: Additional measures were taken by including warning_level VERBOSE and language ECMASCRIPT5 in the header of the test case. Despite these efforts, the issue of {Array.<string>} evasion remains unresolved.

Answer №1

The current type checker has a limitation when it comes to arrays. The right side is typed as "Array" (also known as Array<?>) instead of being specifically defined as "Array<number>" or "Array<string>", allowing it to be assigned to any type.

While it's possible to improve the type checker for this particular scenario, it becomes more challenging in complex cases because JavaScript arrays are mutable. For instance, if we were to define "[11]" as an Array<number>, adding any other type would be considered illegal. However, arrays in JavaScript are commonly non-homogeneous, as demonstrated by:

var args = [];
args[0] = 1;
args[1] = 'foo';

Therefore, the type of Array should not be restricted to its initial type by default.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoid navigating to the subscribe block when the server sends a response in Angular

When trying to send a request to the server and check the response, I am not seeing any results. The code for sending the request is below: SendVerificationInfo(item: SendVerificationModel): Observable < any > { return this.httpClient.post < any ...

What steps should be taken to identify a new path following a call to router.navigate?

Trying to interrupt a route change using a router guard. When I use: this.router.navigate([“myApp/userProfiles”]); After calling this, it passes through the CanDeactivate interface of the guard. The guard then needs to determine the actual destinatio ...

Maximizing the power of datatables with ajax integration

Exploring pagination with AJAX on datatables.net is something I want to try. I have two input fields where users can enter start and end dates, followed by the table structure below: <table class="table table-hover" id="example"> < ...

Connect 'this' to an imported function using pure JavaScript

function EmployeeListView() { this._html = html; /../ } EmployeeListView.prototype = { registerEmployeeHandler: function (handler) { syncEmployeeList().bind(this); } function syncEmployeeList() { let elList = this._mHtml.querySel ...

Retrieving JSON data via an AJAX call

Similar Question: Sending PHP json_encode array to jQuery I've created a function that searches a database for a specific name using $.post. It returns user details with matching search criteria in JSON format generated by PHP, like this: Arra ...

Having trouble getting AngularJS ngCloak to function properly?

My post category page is supposed to display a message if there are no posts. However, the HTML appears briefly when the page loads and then hides. I thought using ngCloak would solve this issue, but it doesn't seem to be working for me. Here's t ...

New patch request received in Google Sheets, replacing the existing post request

I am transferring 12 cell values from a Google Sheet to a MongoDB database. The purpose behind this action is to merge the 12 cells, perform certain data transformations, and display the output on a frontend interface later on. Moreover, I'm faced wit ...

Beautiful prompt interface for HTML

I'm attempting to create a sweet alert using the HTML option: swal({ title: "HTML <small>Title</small>!", text: "A custom <span style="color:#F8BB86">html<span> message.", html: true }); Instead of just text, ...

Total number of requests made since the previous reset

I'm currently working on developing an API and I need to set up a route like api/v1/status in order to check the server status. This route should return a JSON response with the total number of requests made to the API since it became active. However, ...

Using Typescript, you can specify an array of type <T> within an object

Having a background in JS, I am currently exploring TS. My goal is to create an object with a single field, which is an array of strings, while ensuring strong typing. let container = { items: ['Item 1'] } container.items[0] = 3; // This is i ...

The scroll feature in JavaScript is malfunctioning

After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...

Ways to recycle a section of Javascript for multiple uses on a single page

As a newcomer to website building, I have a query regarding the usage of a JavaScript function designed for a slideshow. My one-page website comprises multiple slideshow units with their own divs, holders, and counters (e.g., 1/4). A JavaScript code contro ...

Executing a function upon loading a page triggered by a submitted form

Recently on my index.php page, I implemented a form that posts data into a third-party newsletter system. After the form submission, the page reloads to index.php?mail&. Is there a way to detect when the page is loaded and determine if the form has bee ...

($rootScope: busy) Applying changes right now

Whenever I try to make changes to the UI grid after refreshing the data, I keep encountering this error message: angular.js:13236 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24apply ...

Arranging a JSON array based on the numerical value within an object

I am interested in sorting an array from a json file based on distances calculated using the haversine library. The purpose is to find geolocations near a specified value and display the closest results first. function map(position){ var obj, ...

Allow the NodeJS application to conduct self-updates using the NPM package manager

Hello, I'm currently exploring ways to add unique functionality to my NodeJS application, but I'm encountering some challenges. What I aim to achieve is as follows: I am interested in implementing a server code update feature from the client si ...

Troubleshooting chained select boxes using jQuery, PHP, and database integration

Although many chained selects are typically done using JSON, I prefer to utilize my database for this purpose. However, I seem to be encountering an issue where the second select box is not loading properly. Instead of displaying the expected content, it&a ...

Angular JS displays an error message when the user selects an input field and fails to provide any input

On my wizard steps application, I have implemented Angular JS validation that displays errors when the user enters and removes a character in the input field. However, I am trying to figure out how to show the error message if the user tabs onto the fiel ...

Using V-model in conjunction with the boostrap-vue b-table component

I am attempting to bind v-model by passing the value inside the items array. However, the binding is not functioning correctly. The main objective here is to utilize a store since all these values are utilized across multiple "wizard" components. Whe ...

Fixed positioning upon scrolling begins prior to reaching the uppermost point (top div)

Currently, I have implemented a feature where #filter (the white select list in my sidebar) becomes fixed when it reaches the top of the page and stays there while scrolling until it reaches the footer and is released. However, I encountered an issue wit ...