There's the compiler option noImplicitAny, which is described this way:
In some cases where no type annotations are present, TypeScript will fall back to a type of
anyfor a variable when it cannot infer the type.This can cause some errors to be missed, for example:
function fn(s) { // No error? console.log(s.subtr(3)); } fn(42);Turning on
noImplicitAnyhowever TypeScript will issue an error whenever it would have inferredany:function fn(s) { /* ~ Parameter 's' implicitly has an 'any' type. */ console.log(s.subtr(3)); }
What I want is to configure the compiler to act even more strictly where type information cannot be inferred in cases like the above: I want it to use unknown at every one of these sites (instead of any). There's another compiler option useUnknownInCatchVariables, which is described this way:
In TypeScript 4.0, support was added to allow changing the type of the variable in a catch clause from
anytounknown. Allowing for code like:try { // ... } catch (err) { // We have to verify err is an // error before using it as one. if (err instanceof Error) { console.log(err.message); } }This pattern ensures that error handling code becomes more comprehensive because you cannot guarantee that the object being thrown is a Error subclass ahead of time. With the flag
useUnknownInCatchVariablesenabled, then you do not need the additional syntax (: unknown) nor a linter rule to try enforce this behavior.
However, that only applies to the exception parameter in a catch clause.
How can the compiler be configured to fall back to unknown in all cases?
At the current time, it's not possible to enable this kind of implicit stricter type safety, but an
implicitUnknownoption has been suggested at ms/TS#27265.