Why doesn't TypeScript perform type checking on a two-dimensional array?

Here's a simple code snippet I've been using to create a 2D array:

type cell = {
  id: string;
};
const board: cell[][];
board = Array(10)
      .fill("")
      .map((x) => Array(10).fill(ANY TYPE CAN GO HERE WHY?));

Oddly enough, when I populate the inner array, I can insert any type of data without encountering any errors. Usually, I would expect to only be able to input objects of type cell. Why is this happening?

I'm aware that I should probably specify a type for Array(10), but shouldn't TypeScript then throw an error since "cell" is not included in any union type?

Why isn't type checking enforced in this situation?

Could this convoluted method be causing issues with inferred types?

Answer №1

Array() results in any[], and TypeScript automatically converts it to cell[] without raising any concerns.

This raises 3 important questions:

  • Why does TypeScript convert any to cell? This is a core aspect of TypeScript and must be handled with caution.

Let's consider a similar scenario:

type cell = {
    id: string;
};

const foo: any = "foo";
const c: cell = foo;
  • Why does Array(10) yield any[]? It's because there is no way to determine the type of value at this point. However, Array<cell>(10) returns a cell[].
  • Why does fill(obj) result in any[] instead of (typeof obj)[]? This may be due to the fact that fill modifies the object it operates on, keeping its original type intact.

The key issue here is that any can always be converted to other types, posing a potential risk as TypeScript sometimes undermines its own typing mechanisms.

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

This TypeScript issue in ServiceStack ignores namespaces, leading to duplicate declarations

Currently, I am exploring NativeScript and Angular2 with ServiceStack in C# as the backend. To develop the application, I utilized the typescript-ref command to generate TypeScript classes for use with the JsonServiceClient in ServiceStack: >typescrip ...

Order a portion of a JSON array according to another part of the same array

Having a json array that needs sorting in JavaScript. The EventName field should match the respective Age fields like 01-10 Days and 10-20 Days. [ {Age: "01-10 Days", EventName: "Invoice AP Review", Value: 1, ActiveInvoices: []} ,{Age: "01-10 Days", Even ...

Positioning the search bar to the left with react-bootstrap-table

Is there a way to move the search bar of react-bootstrap-table to the left instead of keeping it on the right? You can see an example here, at the bottom of the page: I know that you can create a custom search panel and input, but that seems like a compl ...

How can we retrieve string values from arrays in Plist files?

Within my project, there exists a Plist file housing various arrays. Each array represents a distinct category and contains further arrays for individual questions. The challenge I am encountering pertains to accessing the nodes and their respective values ...

Arranging items in an ArrayObject using PHP

Upon running this code, I encountered the error message below - Warning: sort() expects parameter 1 to be array. $array1 = new ArrayObject(); $array1->append("50"); $array1->append("30"); $array1->append("60"); sort($array1); // The expect ...

What is the best way to divide an array into groups of four elements when using ngFor

Is there a way to divide an array into groups of four when using ngFor? How can I display four projects at a time instead of one? <div *ngFor="let item of items$ | async"> // How can I show here 4 projects instead of one? {{item}} ...

Tips for deactivating a specific value or graying it out within the list of value items in a drop-down menu using <ng-selectize> or <options> in Angular 7

I am facing a situation where I have to dynamically generate a list of options for a dropdown menu in my Angular 7 application. However, I need to be able to disable specific options in the list based on certain conditions or flags. For example: I am disp ...

deleting element from array once found

I am facing a problem and need some help. let numbers = [1, 2, 3, 4, 5]; let toRemove = [2, 3]; I want to remove 'toRemove' from 'numbers' using the inArray method. if($.inArray(toRemove, numbers) === 1) numbers.remove(toRemove); ...

Ensuring Immutability of React Props in TypeScript

Someone mentioned that React Props are typically read-only, but I noticed that I was able to overwrite the props value in a component without encountering any errors. Is there a way to make props truly read-only? interface Props { readonly isText: bool ...

Discovering the highest value within an array

In my programming project, I have two essential classes - DataClass and MY GUI Class. Within MY GUI Class, there is a specific implementation that involves utilizing an ArrayList called MarksData to store instances of DataClass. final ArrayList<DataC ...

What is the specific term for an event that exclusively passes type arguments into a generic function within the realm of TypeScript?

Currently delving into the world of typescript generics, I recently crafted a generic function as shown below: function getRandomElement<T>(items: T[]): T { let ranIndex = Math.floor(Math.random() * items.length); return items[ranIndex]; } ...

Restricting HTTP requests to once every 200 milliseconds in Angular 4 with filtering in place

In my current project, I am working on a page that utilizes an ngFor to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field. Since the data f ...

I was recently tasked with manipulating a sequence of numbers in a stream, such as 1,3,5,4,6,9. My objective was to display them in a compressed format, showing

When presented with a stream of numbers such as 1,3,5,4,6,9, I was tasked with printing them in the format 1,3-6,9. To achieve this, I devised a solution that involved maintaining a minimum of 2 numbers in a maxHeap and a maximum of 2 numbers in a minHea ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Modify marker location as data updates

I am currently utilizing the Google Maps API within a Vue.js project. In my project, I have a table of data that includes positions, and I am looking to update the marker positions dynamically without refreshing the entire card. Below is the code snippet ...

Handling arrays concurrently

My latest Java project requires me to compare values and/or indexes in multiple arrays. The task involves asking the user to input five letters (either upper or lowercase) and storing them in an array called "lettersArray". Additionally, I have two other a ...

Encountered an issue where property scrollToBottom is unable to be read of null upon returning to

Your system information: Cordova CLI: 6.4.0 Ionic Framework Version: 2.0.0-rc.4 Ionic CLI Version: 2.1.14 Ionic App Lib Version: 2.1.7 Ionic App Scripts Version: 0.0.47 ios-deploy version: Not installed ios-sim version: Not installed OS: Windows 7 ...

Setting up the environment variable for ApolloClient to be utilized in server-side rendering for continuous integration/continuous deployment involves following a specific

My apolloClient is configured as follows: /** * Initializes an ApolloClient instance. For configuration values refer to the following page * https://www.apollographql.com/docs/react/api/core/ApolloClient/#the-apolloclient-constructor * * @returns Apoll ...

What is the best way to fill an array with dates that are not empty?

Is there a way to automatically identify the earliest valid date from a series of values and then assign it to a field in my application? This process currently works smoothly when all fields (starting with @CUST) contain valid date values, but encounter ...

Managing memory usage in Vue 2 when dealing with a high volume of data (approximately 50,000 objects)

I am in the process of creating a table view for large collections of moderately complex objects using Vue 2. The concept involves fetching anywhere from 50,000 to 100,000 rows from a database and storing them in a JavaScript cache. These rows are then dyn ...