Sub topic 8
Remove implicit any
This chapter assumes you have a working tsconfig.json, have renamed at least one .js file to .ts, and can read basic compiler errors. It covers where implicit any comes from, how to turn on noImplicitAny without strict mode, and how to remove each kind of implicit any with a real type.
What implicit any is
TypeScript uses the type any when it cannot work out a type and you have not written one. This is an implicit any. The compiler stops checking that value. You can read any property from it, call it, or pass it anywhere, and TypeScript reports nothing.
function double(value) {
return value * 2;
}
double("abc"); // no error, returns NaN at runtimeWith strict off, value is silently typed as any. The call compiles, and the bug appears only at runtime.
An explicit any is different. You wrote it, so the choice is visible in the code and easy to search for. An implicit any is hidden. A migrated file that is full of them looks typed but gives almost no protection.
Turn on noImplicitAny alone
The noImplicitAny option makes the compiler report an error wherever it would have fallen back to any. It is one of the flags that strict turns on, and you can enable it by itself while the other strict flags stay off.
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false,
"noImplicitAny": true
},
"include": ["src"]
}An individual flag set explicitly overrides the value implied by strict. This lets you stage the migration: noImplicitAny first, then strictNullChecks, and strict last.
The same double function now fails:
function double(value) {
return value * 2;
}The compiler reports error TS7006: Parameter 'value' implicitly has an 'any' type. The code is the useful part. TS7006 is a parameter, and you will meet several related codes.
Where implicit any appears
| Code | Message (shortened) | Typical cause |
|---|---|---|
| TS7006 | Parameter implicitly has an 'any' type | Function parameter with no annotation and no context |
| TS7005 | Variable implicitly has an 'any' type | Variable whose type cannot be inferred |
| TS7034 | Variable implicitly has type 'any' in some locations | `let x;` captured by a closure |
| TS7031 | Binding element implicitly has an 'any' type | Destructured parameter with no type |
| TS7053 | Element implicitly has an 'any' type because expression can't be used to index | Indexing an object with an arbitrary string |
| TS7016 | Could not find a declaration file for module | Untyped third-party package (covered in a later chapter) |
Most errors in a freshly renamed file are TS7006 and TS7031. The rest of this chapter goes through the fixes in the order you are likely to meet them.
Parameters that need an annotation
A parameter gets a type from context in only one case: when the function is passed where a typed function is expected. Anywhere else, you annotate it yourself.
const numbers = [1, 2, 3];
// No annotation needed: the callback's parameter is inferred as number.
const doubled = numbers.map((n) => n * 2);
// Annotation needed: nothing tells TypeScript what `value` is.
function double(value: number): number {
return value * 2;
}This is called contextual typing. The map callback gets n: number because numbers is number[]. If you write a callback and the compiler still complains, check that the receiving function is itself typed.
To pick the annotation, look at how callers use the function. Search for call sites, and read the function body for operations like .toUpperCase() or arithmetic. If callers pass more than one type, use a union such as string | number and handle each case inside the function. Avoid the shortcut of annotating any, because that removes the error and keeps the hole.
Destructured parameters
Destructuring hides the parameter's type. The compiler reports TS7031 for each destructured name.
// error TS7031: Binding element 'name' implicitly has an 'any' type.
function greet({ name, age }) {
return name + " is " + age;
}Adding a type to each name inside the braces does not work, because { name: string } there means "rename name to string". Annotate the whole pattern after it:
interface Person {
name: string;
age: number;
}
function greet({ name, age }: Person): string {
return name + " is " + age;
}An inline object type works for one-off helpers: function greet({ name, age }: { name: string; age: number }). Use a named interface when two or more functions share the shape.
Variables that start empty
A variable declared without a value has nothing to infer from.
let result; // implicit any, evolves with assignments
result = 5;
result = "five";In some cases TypeScript tracks the variable as it is assigned (an "evolving any"), and the error appears only when the variable is captured in a closure (TS7034). Do not rely on that. Give the variable a type at its declaration:
let result: number | undefined;Empty arrays behave the same way. const items = []; is an evolving array, and reading it from a nested function triggers TS7034. Annotate it:
interface Item {
id: number;
label: string;
}
const items: Item[] = [];Indexing with a string key
Objects used as dictionaries are common in JavaScript. Indexing them with a variable key produces TS7053.
const prices = { apple: 1, pear: 2 };
function priceOf(fruit: string): number {
return prices[fruit]; // error TS7053
}The object type has two known keys, and string could be any string. There are two good fixes, depending on what the object really is.
If it is a fixed set of keys, narrow the key type:
const prices = { apple: 1, pear: 2 };
function priceOf(fruit: keyof typeof prices): number {
return prices[fruit];
}If it is an open dictionary, give it an index signature:
const prices: Record<string, number> = { apple: 1, pear: 2 };
function priceOf(fruit: string): number | undefined {
return prices[fruit];
}The second version returns number | undefined because a missing key yields undefined at runtime. By default TypeScript types prices[fruit] as number, so declaring the honest return type is a choice you make. Setting noUncheckedIndexedAccess makes the compiler enforce it.
Callbacks and event handlers
When you pass a function to an untyped API, there is no context. If you define the handler separately from where it is used, annotate it.
type Handler = (message: string) => void;
const handlers: Handler[] = [];
function onMessage(handler: Handler): void {
handlers.push(handler);
}
onMessage((message) => console.log(message.length)); // message: stringDefining the type once, as Handler, means every place that uses it gets the same contextual typing.
Return types
Return types are inferred from the function body, so they rarely trigger noImplicitAny. A function with a recursive call is the main exception, where the compiler reports TS7023 (implicitly has return type 'any' because it does not have a return type annotation and is referenced in its own return expression). Annotate the return type there.
Even where inference works, write return types on exported functions. An inferred return type changes silently when the body changes, and callers elsewhere can break. A written return type makes the compiler check the body against your intent.
What to do when you cannot know the type
Sometimes the honest answer is that the type is not known until runtime, such as parsed JSON or a value from a message queue. Use unknown rather than any:
function parse(text: string): unknown {
return JSON.parse(text);
}
const value = parse('{"port": 8080}');
// value.port; // error: 'value' is of type 'unknown'unknown accepts any value but forbids use until you check it. That keeps the compiler working for you. Later chapters cover narrowing and assertions in detail.
For a single stubborn line, a deliberate explicit any with a comment is acceptable, and is better than hiding it:
// TODO(migration): type this once the legacy API has a schema.
const legacy: any = getLegacyPayload();You can find these later with a search for : any or with a lint rule that bans explicit any.
A workflow for clearing the errors
- Turn on
noImplicitAnyand runnpx tsc --noEmit. - Sort the errors by file and fix one file at a time.
- Start with functions that other code calls. Their annotations give callers their types.
- Replace repeated inline shapes with an interface or type alias.
- Re-run the compiler after each function. Fixing one annotation often removes several errors in other places.
Common mistakes
- Writing
: anyeverywhere to silence errors. The error count drops and the safety does not improve. - Annotating the inner name in a destructured parameter, which renames it instead of typing it.
- Fixing only the call site. The function signature is the place to fix.
- Expecting
noImplicitAnyto catchnullproblems. Those needstrictNullChecks, which a later chapter covers.
Exercise
The function function label({ id, title }) { return id + ": " + title; } fails under noImplicitAny with TS7031. Rewrite it so it compiles, with id as a number and title as a string, and say why { id: number, title: string } placed inside the braces would be wrong.
Show answer
Write interface Entry { id: number; title: string } and function label({ id, title }: Entry): string { return id + ": " + title; }. Placing : number after id inside the braces is destructuring syntax for renaming, so { id: number } would bind the property id to a new local variable called number and leave it untyped. The type annotation must follow the whole pattern.
Exercise
Given const stock = { pens: 10, paper: 4 }; and function count(item: string) { return stock[item]; }, give two fixes for TS7053 and state which one is right when item comes from user input.
Show answer
Fix 1: change the parameter to item: keyof typeof stock, which allows only "pens" or "paper". Fix 2: declare const stock: Record<string, number> = { pens: 10, paper: 4 };, which accepts any string key. For user input, use the Record version and return number | undefined, because the user can send a key that does not exist.