Description
⭐ Suggestion
Currently there's useUnknownInCatchVariables
which allows changing the error type in catch to unknown (from any) by default.
Using the same reasoning why that option was introduced, I think it would make sense for 1 or 2 more options in a similar vein:
-
useUnknownForAnyReturn: if a function returns "any", treat it as if it were "unknown" when the function is called. This is useful especially with 3rd party libs, but also in general, since "unknown" is much stricter than "any" (which is one of the reasons e.g. @typescript-eslint has a "no-unsafe-assignment" rule - which often cannot be fixed, since the "any" comes from a third party package)
-
useUnknownForAnyParamCallback: if a function/callback does not have any types specified, the default is any. It would make checking better if it would be treated as "unknown" instead of "any", when this flag is set.
🔍 Search Terms
All mentioned in the suggestion above
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
📃 Motivating Example
import foo from 'foo';
const bar = foo(); // foo returns any
acceptsStringOnly( arg ); // no error reported, since "any" is allowed for string, but when running the code in browser, this will give an error, that tsc could easily catch, if it were "unknown" instead of "any"
if ( arg === false ) {
// arg is still type "any", because type guard doesn't work on "any"
}
💻 Use Cases
Stricter type checking to avoid bugs popping up when using 3rd party code/any return, where that value is used in functions that have stricter requirements.
If you look at error data (e.g. sentry) you will see that this is actually the most common error reported from users browsers, as the "any" is an escape hatch from the type system, making type validation in typescript useless in some cases - which is the reason why the useUnknownInCatchVariables
was implemented already.