How to configure the compiler to implicitly use `unknown` instead of `any` in cases where it fails to infer type information?

179 views Asked by At

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 any for 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 noImplicitAny however TypeScript will issue an error whenever it would have inferred any:

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 any to unknown. 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 useUnknownInCatchVariables enabled, 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?

1

There are 1 answers

0
jsejcksn On

At the current time, it's not possible to enable this kind of implicit stricter type safety, but an implicitUnknown option has been suggested at ms/TS#27265.