Triggering TypeScript error due to missing type annotations for arrays

When I type const array = [], TypeScript automatically infers it as any[].

I have been looking for a solution to make this fail linting, but so far I have not found any rule in either ESLint or TypeScript that can help with this.

const array = []; //array currently inferred as any
array.push('test'); //array currently inferred as string[]
array.push(1); //array currently inferred as (string | number)[]

Answer №1

There isn't a specific guideline for this situation within the core ESLint or typescript-eslint modules. I checked for any plugins created by the community, but couldn't find one.

In the meantime, you can partially address this issue using the built-in rule no-restricted-syntax. This rule can be customized to target specific ESQuery selectors. For example, you can configure it to identify and flag variable declarations that lack type annotations and initialize an empty array:

"no-restricted-syntax": [
  "error", 
  {
    "message": "Don't use evolving any arrays.",
    "selector": "VariableDeclarator:matches([id.typeAnnotation=undefined]):matches([init.type=ArrayExpression]):matches([init.elements.length=0])"
  }
]

Here's a typescript-eslint playground demonstrating this in action. It may be possible to refine the selector for better precision.


An alternative approach would involve creating a dedicated lint rule specifically for this scenario. This would eliminate the need to handle no-restricted-syntax settings, which can become complex when dealing with ESLint configuration overrides, and could provide automated fixes/suggestions as well.

I suggest considering submitting an issue on typescript-eslint. Upon searching, I didn't come across any existing discussions related to arrays without type annotations or other similar topics. Checking for duplicate issues using different search terms could help ensure no prior discussions exist.

If this enhancement doesn't get implemented as a plugin rule in typescript-eslint, there's always the option of developing your own custom ESLint rule and publishing it as a standalone plugin. The typescript-eslint.io > Custom Rules documentation provides guidance on working with the tooling for custom rules.

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

Search timeout restriction

I have a function that makes a request to the server to retrieve data. Here is the code for it: export default class StatusChecker { constructor() { if (gon.search && gon.search.searched) { this.final_load(); } else { this.make_req ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Retrieve the values of a dynamic JSON object and convert them into a comma-separated string using Typescript

I recently encountered a dynamic JSON object: { "SMSPhone": [ "SMS Phone Number is not valid" ], "VoicePhone": [ "Voice Phone Number is not valid" ] } My goal is to extract the va ...

Combine the AnimatedMarker from leafletjs with typescript

After installing leaflet typescript, I encountered issues when trying to use leaflet non-typescript plugins. For instance, I had no problem importing the leaflet-routing-machine plugin by following these steps: installation: npm install --save leaflet-ro ...

Transitioning from one provider to another and encountering the error message "Cannot read property prompt of undefined."

This is an example of an alert service in TypeScript public Alert = { prompt: () => { return new Promise((resolve, reject) => { let prompt = this.alertCtrl.create({ title: 'Enter username', ...

The type 'contextPaneTitleText' argument cannot be assigned to the parameter type 'key of RemoteConfig'

I am encountering an issue when using the following code snippet: const contextPaneTitleText = useFeature("contextPaneTitleText").asString(); This code is resulting in an error message: Argument of type '"contextPaneTitleText" ...

Encountering an error "Property is used before its initialization" in Angular 10 when attempting to input an object into a template

My code includes a class: import * as p5 from 'p5'; export class Snake{ constructor() { } sketch = (p: p5) => { p.setup = () => { ... } } } To instantiate this class in app.component, I do the follow ...

Angular 4 incorporates ES2017 features such as string.prototype.padStart to enhance functionality

I am currently working with Angular 4 and developing a string pipe to add zeros for padding. However, both Angular and VS Code are displaying errors stating that the prototype "padStart" does not exist. What steps can I take to enable this support in m ...

"Combining the power of AngularJS2 beta with Spring Boot: the ultimate

I am currently using Atom 1.4.0 with the atom-typescript package to develop AngularJS2 modules in TypeScript. On the backend, I have a spring-boot application for handling the REST APIs. After making changes to the .ts files in Atom, it seems to compile t ...

Exploring the effectiveness of testing Svelte components

Looking to test a component that utilizes a third-party module without mocking the imported components? Check out this example: // test.spec.ts import Component from "Component"; describe('Component', () => { test('shoul ...

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

Error: The Select2 query service is not available

I am looking to enhance the search functionality for my select2 dropdown. My goal is to trigger a service call with the search parameters once 3 characters are typed into the search field. However, when I try to select an option from the dropdown, I encou ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

Removing a portion of an item with the power of RxJS

I possess the subsequent entity: const myObject = { items:[ { name: 'John', age: 35, children: [ { child: 'Eric', age: 10, sex: 'M' }, { ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Experimenting with error boundaries by utilizing the React Testing Library and Jest:

I am facing an issue while writing a test for my error boundary higher-order component (HOC). The problem arises when I mock throwing an error in my wrapped component, causing the test to fail because it recognizes the error as a genuine one instead of und ...

Declaration of types for invoking the lodash `mapKeys` function

Is there a way to create a function that can map object keys from camelCase to snakeCase, and be used multiple times with different objects? I have already written a function called mapKeysToSnakeCase which does the job, but I'm curious if there is a ...

Turn TypeScript - Modify type properties to reflect types of their descendants

I am currently working on creating a type that will modify a generic type based on its children. To provide some clarity, I have created a simplified example below: Original type type FormFields = { username: { type: string, ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

Showing identification and name within a URL path - Angular

I am looking to update a URL path within a website from http://localhost:4200/viewbrand/1 to http://localhost:4200/viewbrand/1/soap, where "soap" is added after the ID in the path. The current code in the routing module.ts file is as follows: { path: &apo ...