Skip to main content

no-inferrable-types

Disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean.

🎨

Extending "plugin:@typescript-eslint/stylistic" in an ESLint configuration enables this rule.

🔧

Some problems reported by this rule are automatically fixable by the --fix ESLint command line option.

TypeScript is able to infer the types of parameters, properties, and variables from their default or initial values. There is no need to use an explicit : type annotation on one of those constructs initialized to a boolean, number, or string. Doing so adds unnecessary verbosity to code -making it harder to read- and in some cases can prevent TypeScript from inferring a more specific literal type (e.g. 10) instead of the more general primitive type (e.g. number)

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-inferrable-types": "error"
}
};

Try this rule in the playground ↗

Examples

const a: bigint = 10n;
const a: bigint = BigInt(10);
const a: boolean = !0;
const a: boolean = Boolean(null);
const a: boolean = true;
const a: null = null;
const a: number = 10;
const a: number = Infinity;
const a: number = NaN;
const a: number = Number('1');
const a: RegExp = /a/;
const a: RegExp = new RegExp('a');
const a: string = `str`;
const a: string = String(1);
const a: symbol = Symbol('a');
const a: undefined = undefined;
const a: undefined = void someValue;

class Foo {
prop: number = 5;
}

function fn(a: number = 5, b: boolean = true) {}
Open in Playground

Options

This rule accepts the following options:

type Options = [
{
ignoreParameters?: boolean;
ignoreProperties?: boolean;
},
];

const defaultOptions: Options = [
{ ignoreParameters: false, ignoreProperties: false },
];

ignoreParameters

When set to true, the following pattern is considered valid:

function foo(a: number = 5, b: boolean = true) {
// ...
}
Open in Playground

ignoreProperties

When set to true, the following pattern is considered valid:

class Foo {
prop: number = 5;
}
Open in Playground

When Not To Use It

If you strongly prefer to have explicit types regardless of whether they can be inferred, this rule may not be for you.

Further Reading

Resources