Search code examples
typescripttype-inferencetypescript-eslinttypescript-typesimplicit-typing

Show warning when using implicit type in typescript


I'd like to make vscode to show warning when I do not annotate type even if typescript infer type correctly (I'm not talking of noImplicitAny option).

Is there an option in tsconfig that could allow me to have this behavior ?


Solution

  • TypeScript itself doesn't have a setting that will warn you if you don't annotate a variable whose type can be inferred. The only time such things are considered a problem in the language is if the inference fails and the type implicitly falls back to the any type.

    For functionality like this, you might want to use a linter like ESLint with a rule like @typescript-eslint/typedef, whose description reads

    This rule can enforce type annotations in locations regardless of whether they're required. This is typically used to maintain consistency for element types that sometimes require them.

    Note: this is not necessarily recommended: the official TS handbook about annotations implies that you should normally just rely on the inferred types, and even the ESLint rule linked above says :

    ⚠ CAUTION

    Requiring type annotations unnecessarily can be cumbersome to maintain and generally reduces code readability. TypeScript is often better at inferring types than easily written type annotations would allow.

    Instead of enabling typedef, it is generally recommended to use the --noImplicitAny and --strictPropertyInitialization compiler options to enforce type annotations only when useful.