Is it considered poor practice to specify the type explicitly when it can be easily inferred by Tslint?

When using VSCode, the linter tslint may raise an issue when the following code is added with a specific type:

serverId: number = 10;

This will trigger the following message:

[tslint] Type number trivially inferred from a number literal, remove type annotation (no-inferrable-types)

If 'number' is removed as the type, the message disappears.

What is the reasoning behind it being considered bad practice to specify the type in this scenario?

Answer №1

While it may not be considered a bad practice, including serverId: number = 10 in your code is unnecessary as the number type is automatically inferred by TypeScript when assigning a value to a property. The TSLint rule no-inferrable-types highlights this:

Explicitly specifying types where they can be easily deduced by the compiler only adds unnecessary verbosity to your code.

Unless there is a specific scenario where the serverId property could start as undefined and get defined later (such as within a constructor function), omitting the number type declaration is recommended.

This approach works seamlessly with the noImplicitAny option, ensuring that all types are explicitly declared and nothing is left to chance due to accidental omissions during inference.

Answer №2

It has been pointed out that including both the type and value in code can be seen as unnecessary repetition and may come off as cluttered. Despite this perspective, I personally find it helpful to have both pieces of information for various minor workflow reasons. In my opinion, the level of clutter caused by this redundancy does not warrant implementing a strict rule against it. However, if you prefer to disable it, here's how you can do so:

  • Open your tslint.json file
  • Locate the "no-inferrable-types" attribute
  • Add ignore-properties to its array

For more information, refer to the relevant tslint documentation at

Answer №3

If you are in search of a solution for ESLint after realizing that tslint is no longer supported, simply include this rule in your ESLint configuration:

module.exports = {
  // ...
  rules: {
    // ...,
    "@typescript-eslint/no-inferrable-types": "off",
    ...
  },
};

Answer №4

The root cause of this issue can be found in the tslint.json configuration file.

To resolve it, you have a few options. You can either initialize your variable like this:

serverId = 10;

or declare it as a number:

serverId: number;

You can also adjust the configuration for no-inferrable-types in your tslint.json file:

no-inferrable-types: false

Answer №5

There is no need for this response as it adds no value or new insights. It simply reiterates the fact that "10 is a number".

Answer №6

It may seem strange to bring this up now, but I encountered a similar error and couldn't locate the "no-inferrable-types" attribute in the tslint.json file of my angular application. I'm not sure why it wasn't there initially, but I had to manually insert it like so:

"rules": {
    **"no-inferrable-types": false,**
    "directive-selector": [
      true,
      "attribute",
      "app",
      "camelCase"
    ],

After adding that line, everything started working perfectly!

P.S. This is for anyone else facing the same issue I did, or I could be mistaken because none of the solutions I found mentioned that we need to add this configuration manually in the json file.

Answer №7

Make sure to include or update the following rule in your tslint.json file:

"no-inferrable-types": [
  true,
  "ignore-params",
  "ignore-properties"
]

Answer №8

Some may interpret it as distracting background chatter. Emphasizing the significant components is what truly matters.

Answer №9

In the helpful documentation provided at ,

According to TypeScript, types can be inferred from default or initial values for parameters, properties, and variables. There is no need for explicit : type annotations when initializing constructs with boolean, number, or string values. Adding unnecessary verbosity to code can make it harder to read and sometimes prevent TypeScript from inferring a more specific literal type.

Simply writing serverId = 10 will prompt TypeScript to automatically recognize serverId as a number.

Answer №10

To fix this problem in Angular version 13 or higher, you can include the following rule in your .eslintrc.json file:

"@typescript-eslint/no-inferrable-types": [
      "error",
      {
        "ignoreProperties": true
      }
    ],

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

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

Why does my ngFor consistently refresh while the array remains unchanged?

Issue at hand: Whenever I launch this component, the ngFor div continuously updates and causes my RAM to deplete. Typically, ngFor is triggered when the array is updated; however, in my case, the array (announcements) only updates once in the constructor. ...

"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000. Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header However, when checking the storage &g ...

Leverage the power of react-redux useSelector with the precision of TypeScript

When attempting to utilize the new useSelector hook (shown in the example below) from react-redux in TypeScript, an error is encountered indicating that the function does not exist: Module '"../../../node_modules/@types/react-redux"' has no expo ...

creating a fresh instance of a class while in a subscribe method

Although this code is functional, it briefly displays incorrect data because a blank token is instantiated before being populated in the subscribe function. Is there a way to move the instantiation into the subscribe function or provide all necessary par ...

Utilize NodeJS and Typescript to input data into a postgreSQL database

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

The Material Table in Angular is having issues with sorting functionality

I tried implementing the basic example from the angular material website, which displays a table with accurate data but the sorting functionality is not working as expected. For reference, you can view the StackBlitz demo here: https://stackblitz.com/edit ...

Tips for resolving Typescript type error when overriding MuiContainer classes

My application is divided into two main files: (https://codesandbox.io/s/react-ts-muicontainer-override-yywh2) //index.tsx import * as React from "react"; import { render } from "react-dom"; import { MuiThemeProvider } from "@material-ui/core/styles"; imp ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

Typescript Syntax for Inferring Types based on kind

I'm struggling to write proper TypeScript syntax for strict type inference in the following scenarios: Ensuring that the compiler correctly reports any missing switch/case options Confirming that the returned value matches the input kind by type typ ...

In Angular with rxjs, make sure the response is set to null if the json file cannot be found during an http.get request

When working on my Angular app, I often retrieve data from a static JSON file like this: @Injectable() export class ConfigService { constructor(private http: HttpClient) { } getData() { this.http.get('/assets/myfile.json').subscribe(da ...

Error in Mongoose Schema Configuration Detected in NestJS App

I'm currently developing an e-commerce application using NestJS and MongoDB with Mongoose. I've been facing an issue while trying to implement a user's shopping cart in the application. The error message I keep encountering is as follows: ...

Hide the navigation menu when a page link is selected

Within my Angular 8 application, a fixed navigation bar is positioned at the top of the screen. Upon hovering over a dropdown nav link, a menu will appear for the user to explore. However, when a user clicks on one of these menu links, Angular Routing is ...

What is the process for debugging a project that is not the "main" one?

I am facing an issue with Visual Studio Code where I have two directories in my workspace, both of which are node.js projects. However, I am only able to launch one of them for debugging. Even though both folders have a launch.json file, only the first fol ...

Angular: implementing a service for conditional module imports

Currently, I have a service that is responsible for loading a list of modules: @Injectable() export class MyService { public allowedModules: any = this.modulesFilter(); constructor() { } public modulesFilter() { const testPef = true; co ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Issue: [ts] Unable to locate the term 'React'

Due to specific requirements, I have made some customizations to the Ionic component: range. I changed the class name of the component from Range to CustomRange (with selector: custom-range): https://github.com/ionic-team/ionic/blob/master/core/src/compon ...

What are the top techniques for designing with Angular 2 Material Design?

As a newcomer to angular 2 material design, I have noticed the primary, accent, and warn classes that apply specific colors to elements. Are these the only styling options available in Angular Material 2? Are there other classes that can be utilized for cu ...