TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results.

For example, when using this line of code:

var coins: { coin: number}[] = [1,1,1]

TypeScript throws an error:

Error TS2322: Type 'number[]' is not assignable to type '{ coin: number; }[]'

Surprisingly, when using this line:

var coins: { coin: number}[] = Array(3).fill(1)

The code compiles successfully without any errors.

This raises the question - is this a bug in TypeScript or is it actually intended behavior? And if so, why does TypeScript allow this kind of array declaration without performing type checking?

Answer №1

The issue arises when using Array(3) to create an array with a length of 3 and type any[], followed by applying the fill method on that array. Because any can be assigned to any type, the array generated as any[] can then be assigned to arrays of other types (such as { coin: number}).

If you were to explicitly provide the type parameter for the Array function, you would receive an error:

var coins: { coin: number}[] = Array<{ coin: number}>(3).fill(1) // 1 cannot be assigned to type { coin: number}

Unfortunately, there is no foolproof way to enforce the inclusion of the type argument for arrays in this scenario.

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

Error: The function concat() is not valid for messagesRef.current

I'm currently developing an app that enables users to interact with AI by asking questions related to the uploaded PDF file. However, I've encountered a problem while interacting with AI on the client side - I keep receiving the error 'TypeE ...

Limiting the display of every item in Angular ngFor

I'm currently working with Angular and I have the following code in my component.html: <div class="card" *ngFor="let item of galleries;" (mouseenter)=" setBackground(item?.image?.fullpath)" (mouseover)="showCount ...

Node.js/TypeScript implementation of the Repository design pattern where the ID is automatically assigned by the database

Implementing the repository pattern in Node.js and Typescript has been a challenging yet rewarding experience for me. One roadblock I'm facing is defining the create function, responsible for adding a new row to my database table. The interface for ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

Adjust the JSON format that is retrieved from an Ajax call

I am working with a JQuery plugin that includes the following code snippet: transformResult: function(response, originalQuery) { } Within this function, I have the task of converting Json data from the originalQuery to the response format: [ { "Id": ...

Are there any similar tools to Graphstream in Java that can be used with HTML5 using canvas and JavaScript?

GraphStream is a revolutionary graph library created in Java that offers Java developers a simple way to visually represent dynamic graphs either in memory, on screen, or in files. Check out this demo video. With GraphStream, you can effectively handle th ...

Organizing Telephone Number Entries in Angular

In my search for a way to format a phone number input field in Angularjs, I have come across many solutions, but none specifically for Angular 7. What I am looking to achieve is for the user to enter the textfield like so: 123456789 and have the textfi ...

"Enhance your forms with RadixUI's beautiful designs for

New to Radix UI and styling components, I encountered difficulties while trying to adapt a JSX component to Radix UI: Utilizing Radix UI Radio Groups, I aim to style my component similar to this example from Hyper UI with grid layout showing stacked conte ...

Retrieve a specific item from a JSON response using Node.js

When I receive a message from a WebSocket, the code snippet is triggered like this: ws.onmessage = (e) => { debugger if (e.data.startsWith('MESSAGE')) alert(JSON.stringify(e.data)) ImageReceived(e.data) c ...

Unable to access property value following AJAX call

Here is my code snippet: constructor(props: any) { super(props); this.state = { list: [], }; } public componentWillMount() { this.loadData(); } public loadData = () => { axios.get(someURL) .then((response) = ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

Guide on how to toggle disabled input text box upon checking checkbox using JavaScript

When the checkbox next to the appended text box is checked, I want to disable that text box. The hard-coded text box is already disabled when its checkbox is checked. You can see the actual outcome by running the code snippet or check out the screenshots b ...

Appending an empty <li> tag has no effect

I'm facing an issue with this loop where it always generates empty <li></li> tags. Can anyone help me understand why this is happening and suggest a solution? For reference, the loop runs 2 times (verified). function a(){ for (var i ...

Merge the movements of sliding a block along with the cursor and refreshing a sprite displayed on the block

Confronted with the challenge of combining 2 animations, one to move the block behind the cursor inside the container and the other to update the sprite on the block. Let me elaborate further on my issue. The block should only move when the cursor is insi ...

Loading Images in Advance with jQuery, Native JavaScript, and CSS

After successfully implementing a method to hover on a small image and load an additional image to the right side of the page, I am now looking to enhance user experience by preloading images. Is there a way to preload an image using JQuery, allowing it t ...

The Express request parameter ID throws an error due to the index expression not being of type 'number', causing the element to implicitly have an 'any' type

Is there a way to assign a type to an ID request parameter? It appears that the types of Express treat request params as any. This is the code snippet where I am trying to access the ID from the request: const repository: Repository = { ...reposit ...

Using identical variable names for functions in Node.js

I'm feeling a bit puzzled about the following code snippet. Is it possible to create a class in JavaScript like this? module.exports = function testName(params){ testName.test = function(req, res){ //some code here } return testName; } Inste ...

What is the best way to incorporate a minimum width and maximum width in CSS that add up to 100% when necessary?

Can anyone help me find CSS rules that can set a fixed width for an element (width: 500px) but also allow it to be responsive with max-width: 100% if the container is narrower than the element? I saw this example and it works perfectly: .elem { width: 60 ...

Dynamic Selection List Population in jqGrid

Using jqGrid 4.13.3 - free jqGrid In the Add form, there is a static input element and a select list element. The keyup ajax function is bound to the input element using dataEvents in the beforeInitData event. Once the Add form is displayed, entering a va ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...