Sub topic 7
Compiler options that surface any and unknown
This chapter assumes you can read a tsconfig.json and run tsc. It covers the compiler options that decide whether any enters your code silently or only when you write it. It also covers the option that makes caught errors unknown.
Two ways any enters a program
A value gets the type any in one of two ways:
- Explicitly. You write
: anyoras any. The compiler assumes you meant it. - Implicitly. The compiler cannot work out a type, so it falls back to
anywithout telling you.
The compiler options in this chapter mostly target the second way. Implicit any is the dangerous one because nobody decided it. The type checker switches off for that value, and no warning marks the spot.
The strict family
The strict option is a shortcut that turns on a group of stricter checks. The checks that matter most for this tutorial are:
| Option | What it does | Relation to any and unknown |
|---|---|---|
| `noImplicitAny` | Reports an error where a type would silently become `any` | Stops implicit `any` |
| `useUnknownInCatchVariables` | Types the variable in `catch (e)` as `unknown` instead of `any` | Turns a hidden `any` into `unknown` |
| `strictNullChecks` | Stops `null` and `undefined` from being assignable to every type | Makes narrowing of `unknown` meaningful |
| `noImplicitThis` | Reports `this` with an implied `any` type | Closes another implicit `any` hole |
Setting "strict": true enables all of these. You can then switch off individual ones by setting them to false. That is the usual path when you migrate an older codebase.
A minimal configuration looks like this:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noEmit": true
},
"include": ["src"]
}Run the check without producing output files:
npx tsc --noEmitThe useUnknownInCatchVariables option exists in TypeScript 4.4 and later. If you are on an older version, upgrade before you rely on the behavior described here.
noImplicitAny in detail
noImplicitAny does not forbid any. It forbids the compiler from picking any on your behalf. Here are the common situations where it reports an error.
Parameters without a type
function double(n) {
// error TS7006: Parameter 'n' implicitly has an 'any' type.
return n * 2;
}Without the option, n is any, and double("abc") compiles. With the option, you must write n: number.
Callback parameters are different. When the compiler can infer the type from context, no error appears:
const doubled = [1, 2, 3].map((n) => n * 2); // n is inferred as numberThis is called contextual typing. The map method expects a function whose first parameter has the array's element type, so n gets that type. You only need annotations where no context exists.
Destructured parameters
function greet({ name, age }) {
// error TS7031: Binding element 'name' implicitly has an 'any' type.
return `${name} is ${age}`;
}Fix it with an annotation on the whole pattern:
function greet({ name, age }: { name: string; age: number }): string {
return `${name} is ${age}`;
}Modules without type declarations
If you import a JavaScript package that ships no types, noImplicitAny reports an error on the import:
import legacy from "legacy-lib";
// error TS7016: Could not find a declaration file for module 'legacy-lib'.You have three options, from best to worst:
- Install a community types package, such as
@types/legacy-lib, if one exists. - Write a small declaration file that describes only the parts you use.
- Add a shorthand declaration, which makes everything from the module
any.
Option 3 looks like this:
// legacy-lib.d.ts
declare module "legacy-lib";It silences the error, but every value that comes from that module is now any. Treat it as a temporary measure and keep it in one file so it is easy to find later.
For option 2, describe just what you call:
// legacy-lib.d.ts
declare module "legacy-lib" {
export default function parse(input: string): { id: number; label: string };
}Variables whose type cannot be determined
TypeScript tracks an empty array's type as you add to it. This is called an evolving type:
const xs = [];
xs.push(1);
const first = xs[0]; // numberWith noImplicitAny on, this works as long as the compiler can follow the flow. It reports an error such as TS7034 only when the variable is used in a place where the type has not been decided, for example inside a closure created before the first push. The fix is to annotate: const xs: number[] = [];.
What noImplicitAny does not catch
The option only covers places where the compiler had to guess. It leaves two large sources of any untouched.
- Explicit annotations.
let x: anyis accepted. You wrote it, so the compiler assumes it is deliberate. - Library declarations that return
any. The standard library saysJSON.parsereturnsany. Thejson()method on a fetchResponsereturnsPromise<any>. Values from these calls areanywhatever your options say.
const data = JSON.parse('{"id": 1}'); // any, even with strict: true
data.missing.property; // compiles, throws at runtimeThe next chapter deals with this by assigning such results to unknown and narrowing them. For now, remember that a green tsc run under strict does not mean the program contains no any.
useUnknownInCatchVariables
JavaScript lets code throw anything: strings, numbers, null, or objects that are not errors. Because of that, the variable in a catch clause could hold any value. Before TypeScript 4.4, the compiler typed it as any, which let you write err.message without a check. That line crashes if someone threw a string.
With useUnknownInCatchVariables enabled, the variable is unknown:
try {
JSON.parse("{");
} catch (err) {
console.error(err.message);
// error TS18046: 'err' is of type 'unknown'.
}Older compiler versions report the same problem as TS2571 with the text Object is of type 'unknown'. You narrow the value before use:
try {
JSON.parse("{");
} catch (err) {
if (err instanceof Error) {
console.error(err.message);
} else {
console.error(String(err));
}
}Opting out for one clause
You can annotate the catch variable as any or unknown explicitly. Both are allowed whatever the option says:
try {
riskyCall();
} catch (err: any) {
// allowed, but now err is unchecked again
console.error(err.message);
}
function riskyCall(): void {
throw new Error("boom");
}Keep this for code where you know exactly what is thrown and want to avoid noise. Writing err: unknown explicitly is also valid and makes the intent clear even in projects that have the option off.
What the option does not cover
The option only affects catch clauses. It does not change the parameter of a promise rejection handler:
Promise.reject(new Error("x")).catch((reason) => {
// reason is any, regardless of useUnknownInCatchVariables
console.error(reason.message);
});The standard library types that parameter as any. If you use .catch(), annotate the parameter yourself: (reason: unknown) => { ... }. The try/catch around an await is covered by the option, so it is often the safer style.
How the options work together
The flags form a chain. noImplicitAny stops silent any. useUnknownInCatchVariables replaces one built-in source of any with unknown. strictNullChecks ensures that unknown narrowed with !== null or === undefined checks behaves as you expect. Without it, null and undefined slip into every type and your guards give weaker guarantees.
Migrating an existing project
Turning on strict in a large JavaScript or loosely typed project can produce hundreds of errors at once. A staged approach keeps the work manageable:
- Start with
"strict": false, then enablenoImplicitAnyalone. Fix errors file by file. - Enable
strictNullChecks. Expect many errors, because every possibleundefinedbecomes visible. - Enable
useUnknownInCatchVariables. These errors are usually quick to fix by addinginstanceof Errorchecks. - Replace the individual options with
"strict": trueand delete the now redundant lines.
Step 4 matters. A project that lists each flag separately will not pick up checks that newer TypeScript versions add to strict. Be aware that upgrading the compiler can then add new errors under strict. Pin the TypeScript version in package.json and upgrade on purpose.
To fix one file at a time, you can use a per-file comment in TypeScript files that you have not yet cleaned up, such as // @ts-nocheck at the top. It is crude, and it hides every error in that file, so track those files and remove the comment as you go. Prefer a configuration that includes only cleaned directories if you can arrange it.
Common mistakes
- Assuming
strictbansany. It does not. It only removes silent cases. - Fixing TS7006 by typing the parameter as
any. This satisfies the compiler and removes the benefit of the option. Use a real type, orunknownif the input really is unknown. - Using
catch (err: any)everywhere. The option exists to force a check. Overriding it per clause by habit brings back the original problem. - Forgetting that
.catch()callbacks are unaffected. Annotatereasonyourself. - Using shorthand
declare module "x";and forgetting it. Every import from that module isanyfrom then on.
Exercises
Exercise
A project has "strict": true. A teammate writes const config = JSON.parse(text); console.log(config.port.toFixed());. Does tsc report an error, and why or why not?
Show answer
No. JSON.parse is declared to return any, and noImplicitAny only reports types the compiler infers silently, not any that comes from a library declaration. The code compiles and can fail at runtime if config.port is missing. The fix is to assign the result to unknown and narrow it.
Exercise
With useUnknownInCatchVariables on, you write somePromise.catch((reason) => console.log(reason.message)). Is reason typed unknown? What should you do?
Show answer
No. The option only affects the variable in try/catch clauses. The reason parameter of .catch() is typed any by the standard library. Annotate it as (reason: unknown) and narrow it with instanceof Error before reading message.