Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tslint - type trivially inferred - Why is it bad practice to include the type here?

In VSCode the linter , tslint, complains when I add the following code, with the type:

serverId: number = 10;

And gives the following message:

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

When I remove the type 'number', the message goes away.

Why is it bad practice to include the type information here?

like image 679
Tony Scialo Avatar asked Oct 17 '17 21:10

Tony Scialo


4 Answers

It is not a bad practice, but serverId: number = 10 is redundant, because number type is inferred when a property is assigned. This is what TSLint no-inferrable-types warns about:

Explicit types where they can be easily inferred by the compiler make code more verbose.

Unless there is a chance that serverId property may be initially undefined but be defined later (for instance in constructor function), number can be safely omitted.

This approach works best with noImplicitAny option because this way there are no chances that a type will be omitted by mistake because it wasn't inferred.

like image 86
Estus Flask Avatar answered Nov 04 '22 21:11

Estus Flask


As was mentioned above, it's technically redundant and can be considered clutter. Personally I don't care for this opinion and prefer to have both the type and the value for a variety of specific minor workflow reasons and I don't consider it to be the level of clutter warranting a rule. If you want to disable it, here's how.

  • open tslint.json
  • find the "no-inferrable-types" attribute
  • add ignore-properties to its array

relevant tslint docs https://palantir.github.io/tslint/rules/no-inferrable-types/

like image 40
Alex Spera Avatar answered Nov 04 '22 21:11

Alex Spera


If you came here looking for an ESLint solution because tslint is being deprecated, add this rule to your ESLint config:

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

like image 38
Paul Razvan Berg Avatar answered Nov 04 '22 21:11

Paul Razvan Berg


This error is due to your configuration in tslint.json file.

Either just initialize your variable as

serverId = 10;

or

serverId: number;

or just set your configuration for the no-inferrable-types in your tslint.json file as

no-inferrable-types: false
like image 30
Pardeep Jain Avatar answered Nov 04 '22 20:11

Pardeep Jain