The compiler option --strict
in TypeScript is a convenient shorthand for multiple individual compiler options that do not require you to annotate variables or parameters extensively. The type inference capability of the compiler allows it to determine types for unannotated variables and parameters, following the preferred convention in most cases. Only when the compiler cannot infer a suitable type and defaults to using any
will --strict
flag an error about missing annotations. This is primarily to discourage the use of the potentially unsafe any
type with --noImplicitAny
.
In the code snippet above, the unannotated constants like app
, port
, req
, and res
are inferred by the compiler to be of specific types without explicit annotations, as if they had been annotated manually.
The only instance where the compiler encounters an issue is within the parameter declaration of the err
variable in the callback function for app.listen()
. Here, since there is no context for determining the type, the compiler resorts to assigning any
as the type for err
, prompting the need for manual annotation:
app.listen(port, (err: any) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
If you desire notifications for every unannotated variable or parameter, consider using linting tools like TSLint or ESLint alongside TypeScript.
TSLint offers rules like typedef
, which mandates the presence of type definitions. Sub-options cater specifically to function parameters and variable declarations.
ESLint provides a similar rule called typedef
that enforces the existence of type annotations, with sub-options available for fine-tuning its behavior.
While these tools can assist in achieving the desired behavior, keep in mind that embracing type inference is generally recommended. As stated in ESLint's documentation for typedef
: "if you do not find writing unnecessary type annotations reasonable, then avoid enforcing this rule."
I hope this information proves helpful; best of luck!
Link to Playground Code